欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

序列换&反序列化

时间:2023-06-08
序列化:把一个对象从内存中存放到硬盘中的过程

//所有要序列化的类都必须实现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();

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。