ObjectInputStream 和 ObjectOutputStream 的作用是,对基本数据和对象进行序列化操作支持。
创建“文件输出流”对应的ObjectOutputStream对象,该ObjectOutputStream对象能提供对“基本数据或对象”的持久存储;当我们需要读取这些存储的“基本数据或对象”时,可以创建“文件输入流”对应的ObjectInputStream,进而读取出这些“基本数据或对象”。
只有支持 java.io.Serializable 或 java.io.Externalizable 接口的对象才能被ObjectInputStream/ObjectOutputStream所操作。
package com.louisgeek.appupdatetool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Created by louisgeek on 2016/8/23.
*/
public class ObjectXXXStreamTest {
static class Person implements Serializable {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
public static void main(String[] args) throws Exception {
File file = new File("d:" + File.separator + "text.txt");
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file));
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
// 将person对象写出到指定的文件
Person person = new Person(1, "heihei", 25);
output.writeObject(person);
// 从文件中读取person对象
Person p2 = (Person) input.readObject();
System.out.println(p2);
output.close();
input.close();
}
}