您的位置:首页 > 编程语言 > Java开发

Java中对象的序列化(实现java.io.Serializable)

2012-10-02 12:12 561 查看
import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.Date;

/*对象的寿命随着生成该对象的程序的终止而终止,

* 有时候需要将对象的状态保存下来,在需要的时候再恢复

* 串行化只能保存对象的非静态成员变量

* */

class test implements java.io.Serializable{

private static final long serialVersionUID = 1L;

private Date loggingDate = new Date();

private String uid;

private transient String pwd;//不是串行化的一部分

test(String user,String password){

uid=user;

pwd=password;

}

@Override

public String toString() {

String password= null;

if(pwd==null){

password="Not Set";

}else{

password=pwd;

}

return "logon info:\n"+"user:"+uid+"\n logging date:"+loggingDate.toString()+"\n password:"+password;

}

public static void main(String args[]){

test logInfo = new test("lisi","123456");

System.out.println(logInfo.toString());

try {

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("logInfo.out"));

out.writeObject(logInfo);

out.close();

} catch (Exception e) {

e.printStackTrace();

}

try {

ObjectInputStream in = new ObjectInputStream(new FileInputStream("logInfo.out"));

test logInfo1 = (test)in.readObject();

System.out.println(logInfo1.toString());

} catch (Exception e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐