序列化与反序列化
序列化的原本意图是希望对一个Java对象作一下“变换”,变成字节序列,这样一来方便持久化存储到磁盘,避免程序运行结束后对象就从内存里消失,另外变换成字节序列也更便于网络运输和传播
-
序列化:把Java对象转换为字节序列。
-
反序列化:把字节序列恢复为原先的Java对象。
-
ObjectOutputStream是将一个对象写入文件:如果使用这个类写入对象,这个对象需要序列化(实现接口Serializable)
-
ObjectInputStream是从文件中读一个对象:反序列化
public static void main(String[] args) throws IOException, ClassNotFoundException {
serialize();
deserialize();
}
//序列化
public static void serialize() throws IOException {
Student student = new Student();
student.setName("kakafa");
student.setAge( 18 );
student.setScore( 100 );
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream( new FileOutputStream( new File("student.txt") ) );
} catch (IOException e) {
e.printStackTrace();
}finally {
objectOutputStream.writeObject( student );
objectOutputStream.close();
}
System.out.println("序列化成功!已经生成student.txt文件");
System.out.println("==============================================");
}
//反序列化
public static void deserialize( ) throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream =
new ObjectInputStream( new FileInputStream( new File("student.txt") ) );
Student student = (Student) objectInputStream.readObject();
objectInputStream.close();
System.out.println("反序列化结果为:");
System.out.println( student );
}


java对象从一个系统传输到另一个系统后无法被反序列化的问题:https://blog.csdn.net/u011489186/article/details/119387642
参考链接:https://mp.weixin.qq.com/s/0EfIUB9E-0Oh_Clwuxswuw
浙公网安备 33010602011771号