就是序列化和反序列化,就是将对象转化字符序列,将字符序列转为对象的过程
package com.tx.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class test{
public static void main(String[] args) throws FileNotFoundException, IOException {
List<Student> list = new ArrayList<Student>();
list.add(new Student("as","男",14));
list.add(new Student("ass","男",18));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data/out.txt"));
//输出流保存的文件名为 my.out ;ObjectOutputStream能把Object输出成Byte流
oos.writeObject(list);
oos.close();//序列化完毕
System.out.println("序列化完毕");
//反序列化
ObjectInputStream oin = null;
oin = new ObjectInputStream(new FileInputStream("data/out.txt"));
List<Student> stulist = null;
try {
stulist = (List<Student>) oin.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for(Student s : stulist) {
System.out.println(s.toString());
}
System.out.println("反序列化完成");
}
}