Java ObjectInputStream 和 ObjectOutputStream
概述
该流可以将一个基本数据和对象进行序列化,或者读取一个基本数据和对象到程序中. 也就是执行了序列化和反序列化的操作
被序列化的对象的类必须实现 Serializable 接口
序列化和反序列化对象的示例
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
// 创建两个商品对象
Product p1 = new Product("冰箱", 1000);
Product p2 = new Product("电视机", 2000);
// 创建对象输出流
output = new ObjectOutputStream(new FileOutputStream("product.obj"));
// 写出两个对象
output.writeObject(p1);
output.writeObject(p2);
// 关闭输出流
output.close();
// 创建对象输入流,读取被持久化的对象
input = new ObjectInputStream(new FileInputStream("product.obj"));
// 打印对象信息
System.out.println(input.readObject());
System.out.println(input.readObject());
// 关闭流
input.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 运行结果