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

JAVA——对象的序列化Serializable

2016-06-24 21:34 351 查看
import java.io.*;
class Person implements Serializable
{
public static final long serialVersionUID = 42L;
private String name;
transient int age;
static String country = "cn";
Person(String name,int age,String country)
{
this.name = name;
this.age = age;
this.country = country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}


这里有几个需要注意的地方:

(1)静态变量不被序列化:static String country = “cn”;

(2)加上transient的变量不被序列化;

(3)编译时候系统会自动计算序列化的一个标识码,为了不让每次修改一点对象就序列化不了,我门可以使用public static final long serialVersionUID = 42L;

import java.io.*;
class ObjectStreamDemo
{
public static void main(String[] args) throws Exception
{
//writeObj();
readObj();
}
public static void readObj()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj()throws IOException
{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi0",399,"kr"));
oos.close();
}
}


ObjectInputStream和ObjectOutputStream是相对应的。

readObject和writeObject是相对应的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: