Java IO的序列化与反序列化是将对象转换为字节流以便存储或传输,以及将字节流恢复为对象的过程。以下是关于这两个概念的详细解释:
java.io.Serializable接口。ObjectOutputStream类将对象写入输出流。import java.io.*;
public class SerializationExample {
public static void main(String[] args) {
try {
// 创建一个对象
Person person = new Person("John", 30);
// 创建输出流
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
// 将对象写入输出流
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in person.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters (if needed)
}
transient修饰的字段不会被序列化。ObjectInputStream类从输入流中读取对象。import java.io.*;
public class DeserializationExample {
public static void main(String[] args) {
Person person = null;
try {
// 创建输入流
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
// 从输入流中读取对象
person = (Person) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Person class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Person...");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
serialVersionUID来确保类的版本兼容性。这两个过程在Java中广泛应用于对象的持久化、网络通信和分布式系统中。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。