对象串行化
来源:互联网 发布:结构设计优化 编辑:程序博客网 时间:2024/05/16 09:06
当调用对象的程序执行结束以后,对象就随之消亡。但是,有时希望将对象的状态记录下来,以便于恢复,这个过程,就叫做对象串行化。
要理解对象串行化,就需要了解两个关键字Serializable和transient。一个对象,要能够串行化,就必须实现Serializable接口。而transient则表明,某个属性不属于串行化的一部分。
如下代码,是一个串行化的示例。将Test中的username串行化到硬盘,而password则否。然后,再用ObjectInputStream将对象从硬盘中读取并恢复,并读取其中的username属性。
import java.io.*;/* * author:Tammy Pi * function:对象的串行化 */public class SerializableTest implements Serializable{class Test implements Serializable{private String username;//表明password不是对象串行化的一部分private transient String password;public Test(String username,String password){this.username = username;this.password = password;}public String toString() {return username+","+password;}}public void test(){Test t = new Test("tammypi","1988");System.out.println(t.toString());//将t持久化到硬盘ObjectOutputStream os = null;ObjectInputStream oi = null;try {os = new ObjectOutputStream(new FileOutputStream("c:\\Test.out"));os.writeObject(t);os.flush();os.close();os = null;oi = new ObjectInputStream(new FileInputStream("c:\\Test.out"));try {Test t1 = (Test) oi.readObject();System.out.println(t1.toString());} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{if(os!=null){try {os.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(oi!=null){try {oi.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public static void main(String[] args){SerializableTest s = new SerializableTest();s.test();}}
对象的串行化并不难,主要是实现Serializable接口,并且配合ObjectOutputStream和ObjectInputStream使用。
- 对象的串行化
- 对象串行化
- 测试对象串行化
- java对象串行化
- 对象的串行化
- php对象串行化
- 对象的串行化
- 对象串行化
- Java 对象串行化
- PHP-对象串行化
- java 对象串行化
- 对象串行化
- 对象串行化和反串行化
- Object Serializable 对象串行化
- 对象的串行化(Serialization)
- 对象的串行化(Serialization)
- java 实现串行化对象
- Java 里对象串行化
- 富web概述
- TabActivity的使用
- Ext3 文件系统错误 Journal has aborted
- 关于数据库的递归查询
- 手机显示屏发展趋势
- 对象串行化
- 数学之美
- 面试 智力题
- vb.net_Excel出力_画像添付
- VC-"应用程序正常初始化失败"-0xc0150002
- 【IPhone开发】This bundle is invalid.The key CFBundleVersion in the Info.plist file must contain a ...
- 唯一编号算法:生成GUID
- 请求重定向与转发的区别
- 0904_两个小题目_二分查找和杨氏矩阵查找