oos.flush
packagejavabasic;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.io.OutputStream;
importjava.util.Date;
publicclassTestq{
publicstaticvoidmain(String[]args)throwsIOException,ClassNotFoundException{
test();
}
publicstaticvoidtest()throwsIOException,ClassNotFoundException{
//序列化:将对象持久化保存到外部文件中
Peoplep1=newPeople(1001,"张1");
Peoplep2=newPeople(1002,"张2");
Peoplep3=newPeople(1003,"张3");
//序列化对象必须实现Serializable接口
//对象序列话主要用到两种流和write方法:
//1:OutputStreamos=newOutputSream("filepath"):创建与相应外部文件之间的字节输出流
//2:ObjectOutputStreamoos=newObjectOutputStream(os):利用OutputStream创建对象输出流,将对象写到外部文件中
//3:oos.writeOject():将对象写到外部文件中eg:类对象,newString(),newDate()对象等
//4:oos.writeInt():基本数据类型写到外部文件中
//对象反序列画即对象序列化的流向相反过程也主要用到两种流和read方法
//1:InputStreamis=newInputStream("filepath");
//2:ObjectInputStreamois=newObjectInputStream(is);
//3:oos.readOject();//注意强制类型转换
//4:oos.readInt();
//例子:
//对象序列化
OutputStreamio=newFileOutputStream("F:\\strong\\JavaseReview\\file\\studb.file");
ObjectOutputStreamoos=newObjectOutputStream(io);
//写入基本数据类型数值,对象引用
oos.writeInt(1001);//
oos.writeObject(p1);
oos.writeInt(1002);
oos.writeObject(p2);
oos.writeObject(newDate());
oos.flush();//注意一定要刷新一下,将数据在关闭之前都写到外部文件中
oos.close();
//对象反序列化
InputStreamis=newFileInputStream("F:\\strong\\JavaseReview\\file\\studb.file");
ObjectInputStreamois=newObjectInputStream(is);
intid1=ois.readInt();
Peoplepeo1=(People)ois.readObject();
System.out.println(id1+""+peo1.getName());
intid2=ois.readInt();
Peoplepeo2=(People)ois.readObject();
System.out.println(id2+""+peo2.getName());
Datedate=(Date)ois.readObject();
System.out.println(date);
ois.close();
}
}