对象的序列化(对象流)
将对象以字节方式序列化,存储到硬盘,或者进行网络中传输。
进行对象的硬盘存储:
1. 使得被存储的对象,必须要实现序列化的接口!
2. 实现序列化接口得类,生成序列化版本号,如未生成,修改类代码结构后,产生:InvalidClassException
3. 读取文件中的序列化对象,以EOFException异常的发生表示读取文件末尾,建议try-catch处理
实现序列化接口的类
public class User implements Serializable{
private static final long serialVersionUID = 1L;//默认生成的版本号,没有该版本号在修改代码后再执行读取操作会抛出异常
private int id;
private String name;
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
主类进行序列化操作
public class FileTset {
public static void main(String[] args) throws IOException, ClassNotFoundException{
User u1 = new User(1,"张三");
User u2 = new User(2,"张四");
User u3 = new User(3,"张五");
User u4 = new User(4,"张七");
//序列化将对象写入文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("e:/source.txt"));//用缓冲流进行包装提高效率
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(u1);
oos.writeObject(u2);
oos.writeObject(u3);
oos.writeObject(u4);
oos.close();
bos.close();
//将文件中的对象读出来
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:/source.txt"));
ObjectInputStream ois = new ObjectInputStream(bis);
Object ob = null;
try {
while(true){
ob = ois.readObject();
if(ob instanceof User) {
ob = (User )ob;
System.out.println(ob);
}
}
}catch (EOFException e) {
System.out.println("读取完毕");
}
}
}