java 如何 进行序列化和反序列化
时间: 2023-10-30 17:09:30 浏览: 29
Java中的序列化是将对象转换为字节流的过程,而反序列化是将字节流转换回对象的过程。Java提供了一个Serializable接口,当一个类实现了Serializable接口时,就可以将其实例序列化为字节流。
序列化:
```java
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(employee);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
```
反序列化:
```java
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee e = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
}
```