ObjectOutputStream
将对象持久化(永久保存在磁盘上)
注意:要保存的对象的类要实现序列化接口(serializable)
构造方法
protected ObjectOutputStream()throws IOException,SecurityException
public ObjectOutputStream(OutputStream out)throws IOException
Code:
持久化ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("对");
arrayList.add("象");
arrayList.add("流");
arrayList.add("测");
arrayList.add("试");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/w.txt"));
//将arrayList持久化
oos.writeObject(arrayList);
持久化自定义类的对象:
/**
* @author maple
*持久化Student, 要实现Serializable接口
*/
public class Student implements Serializable{
/**
* serialVersionUID: 这个值,是在两端【不同的电脑 对象传递之后,比较类型的一个依据】
* 1.本电脑创建了一个学生对象
* 2.当我们把这个对象传递到其他电脑的时候,这个对象,要与其他电脑里面的Student类比较类型 是否一致
* 3.除了判断类型,还会判断serialVersionUID
*/
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
//自己新建一个测试类,将主方法拷贝过去
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Student stu1 = new Student("小米",4);
Student stu2 = new Student("苹果",6);
//进行持久化
/*ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/x.txt"));
oos.writeObject(stu1);
oos.writeObject(stu2);
//这里在最后放入null是为了标志已经到末尾了
oos.writeObject(null);*/
}
ObjectInputStream
将持久化的对象拿出来
构造方法
protected ObjectInputStream()throws IOException,SecurityException
public ObjectInputStream(InputStream in)throws IOException
//读取上面持久化的arrayList
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/w.txt"));
Object readObject = ois.readObject();
System.out.println(readObject);
读取上面自定义Student类的对象
//将持久化的数据拿出来
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/x.txt"));
/*Object object1 = ois.readObject();
Object object2 = ois.readObject();
System.out.println(object1);
System.out.println(object2);*/
Object obj = null;
while ((obj = ois.readObject()) != null) {
System.out.println(obj);
}