ObjectStreamDemo 代码:
import java.io.*;
class ObjectStreamDemo
{
public static void main(String[] args) throws IOException
{
//writeobj();
readObj();
}
public static void readObj() throws IOException
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
try
{
Person p = (Person)ois.readObject();
System.out.println(p);
}
catch(ClassNotFoundException e)
{
}
finally
{
ois.close();
}
}
public static void writeobj() throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi",33));
oos.close();
}
}
Person
Person类:
import java.io.*;
class Person implements Serializable
{
public static final long seriaVersionUID = 42L;
private String name;
int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return name+":"+age;
}
}
序列号并不是随机的,而是根据代码字段按照特定的算法算出来的。