您的位置:首页 > 移动开发 > Objective-C

对象序列化 ObjectInputStream ObjectOutputStream

2016-06-02 14:21 531 查看
如果想把一个java对象持久化,可以用ObjectInputStream和ObjectOutputStream。下面看demo。

//Person类
public class Person implements Serializable{
//声明类的标识,也可以不写,系统会自动生成
static final long serialVersionUID = 42L;
private String name;
private int age;

public Person(String name,int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}


//先写再读
public class ObjectStreamDemo {

public static void main(String[] args) throws Exception{
//      writeObj();
readObj();
}

public static void writeObj() throws IOException
{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("d:\\obj.txt"));
oos.writeObject(new Person("lisi",39));
oos.close();
}

public static void readObj() throws IOException, ClassNotFoundException
{
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("d:\\obj.txt"));
Person p = (Person) ois.readObject();
System.out.println("====person====");
System.out.println(p.getName());
System.out.println(p.getAge());
ois.close();
}

}


注意:如果不想要属性序列化,可以使用transient修饰,另外静态的属性也不能被序列化。

transient private int age;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息