序列化:把一个对象从内存中存放到硬盘中的过程
//所有要序列化的类都必须实现Serializable接口
Dog d=new Dog("来福1","公",23);
File file = new File("f:\图片\dog1");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(d);
//关闭必须由内而外!
oos.close();
bos.close();
fos.close();
System.out.println("ok");
反序列化:将对象从硬盘介质中还原到内存中
File file = new File("f:\图片\dog");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Dog d = (Dog)ois.readObject();
System.out.println(d.getName());
ois.close();
bis.close();
fis.close();
//保存1000只狗
ArrayList dogs = new ArrayList();
for (int i = 0; i < 1000; i++) {
Dog d = new Dog("旺财"+i, "公", i+1);
dogs.add(d);
}
File file = new File("f:\图片\dogs.bak");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(dogs);
oos.close();
bos.close();
fos.close();