Java 之 对象的序列化(FileOutputStream、ObjectOutputStream)与反序列化(FileInputStream、ObjectInputStream)使用示例
0、创建Java对象
Employee.java
/**
* @author: shipleyleo
* @create: 2023-05-31 22:51:48
*/
public class Employee implements java.io.Serializable {
// 加入序列版本号
private static final long serialVersionUID = 1L;
public String name;
public String address;
// 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
public int eid;
public Employee() {
}
public Employee(String name, String address, int eid) {
this.name = name;
this.address = address;
this.eid = eid;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", eid=" + eid +
'}';
}
}
1、序列号Java对象(FileOutputStream、ObjectOutputStream)
OutStreamTest.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 序列化Java对象(OutputStream)
*
* @author: shipleyleo
* @create: 2023-05-31 22:47:39
*/
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 序列化Java对象(OutputStream)
*
* @author: shipleyleo
* @create: 2023-05-31 22:47:39
*/
public class OutStreamTest {
public static void main(String[] args) {
Employee employee = new Employee("张三", "GZ", 1);
try {
// 创建序列化流
FileOutputStream fos = new FileOutputStream("employee.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 写入一个对象
oos.writeObject(employee);
// 释放资源
oos.close();
fos.close();
} catch (FileNotFoundException e) {
// 捕获异常
e.printStackTrace();
} catch (IOException e) {
// 捕获异常
e.printStackTrace();
return;
}
}
}
输出结果:
在项目根目录下生成employee.txt文件,employee.txt的文件内容如下图所示。
2、反序列化Java对象(FileInputStream、ObjectInputStream)
InputStreamTest.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* 反序列化Java对象(InputStream)
*
* @author: shipleyleo
* @create: 2023-05-31 22:47:39
*/
public class InputStreamTest {
public static void main(String[] args) {
Employee employee = null;
try {
// 创建反序列化流
FileInputStream fis = new FileInputStream("employee.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
// 读取一个对象
employee = (Employee) ois.readObject();
// 释放资源
ois.close();
fis.close();
} catch (FileNotFoundException e) {
// 捕获异常
e.printStackTrace();
} catch (IOException e) {
// 捕获异常
e.printStackTrace();
} catch (ClassNotFoundException c) {
// 捕获类找不到异常
System.out.println("Employee class not found");
c.printStackTrace();
}
// 无异常,直接打印输出
System.out.println(employee);
}
}
输出结果:
参考文章