当需要把内存中的对象状态保存到一个文件中中时候,序列化(Serializable)可以很好地解决问题。使用方法如下:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TestTransient {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo("张三", "123456");
System.out.println(userInfo);
try {
// 序列化,被设置为transient的属性没有被序列化
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"UserInfo.out"));
o.writeObject(userInfo);
o.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
// 重新读取内容
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"UserInfo.out"));
UserInfo readUserInfo = (UserInfo) in.readObject();
//读取后psw的内容为null
System.out.println(readUserInfo.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static class UserInfo implements Serializable {
private static final long serialVersionUID = 996890129747019948L;
private String name;
private transient String psw;
public UserInfo(String name, String psw) {
this.name = name;
this.psw = psw;
}
public String toString() {
return "name=" + name + ", psw=" + psw;
}
}
}
为了便于举例所以用了内部类,被持久化的类要实现Serializable接口,这个接口没有任何函数,只是一个标记接口。实现serialization主要靠两个类:ObjectOuputStream和ObjectInputStream。transient 关键字用来修饰不想被序列化的变量,比如密码、卡号等敏感数据。执行例子后在项目目录下会生成名为UserInfo.out的文件
该贴由koei123转至本版2015-2-6 4:50:45