java序列化反序列化面试题
时间: 2023-11-07 12:05:11 浏览: 178
java序列化和反序列化,面试必备
通过实现Serializable接口,Java对象可以进行序列化和反序列化。序列化将对象转换为字节流,以便于存储或传输,而反序列化则将字节流重新转换为原始对象。需要注意的是,序列化和反序列化的类必须具有相同的.class文件,否则会抛出ClassNotFoundException异常。
在进行对象反序列化时,需要提供Java对象所属类的.class文件。下面是一个示例代码:
```java
package test05;
import java.io.*;
public class Main01 {
public static void main(String[] args) throws IOException {
// 创建ObjectInputStream对象、两个Student对象s1 s2
ObjectInputStream objectInputStream = null;
Student student1 = null;
Student student2 = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream("D:/新建文本文档.txt"));
student1 = (Student) objectInputStream.readObject();
student2 = (Student) objectInputStream.readObject();
System.out.println(student1);
System.out.println(student2);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
objectInputStream.close();
}
}
}
}
```
阅读全文