本文主要是介绍对象串行化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当调用对象的程序执行结束以后,对象就随之消亡。但是,有时希望将对象的状态记录下来,以便于恢复,这个过程,就叫做对象串行化。
要理解对象串行化,就需要了解两个关键字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 block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(oi!=null){
try {
oi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args){
SerializableTest s = new SerializableTest();
s.test();
}
}
对象的串行化并不难,主要是实现Serializable接口,并且配合ObjectOutputStream和ObjectInputStream使用。
这篇关于对象串行化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!