import java.io.*;
class Person implements Serializable
{
static final long serialVersionUID = 42L;
String name;
int age;
Person( String name, int age )
{
this.name = name;
this.age = age;
}
public String toString()//重写toString()方法
{
return name + "::" + age;
}
}
import java.io.*;
class ObjectStreamDemo
{
public static void main( String[] args ) throws Exception
{
//writeObj();
readObj();
}
public static void readObj()throws Exception
{
ObjectInputStream sis = new ObjectInputStream( new FileInputStream( "obj.txt" ) );
Person p = ( Person )sis.readObject();
System.out.println( p ); // 为什么在这只是直接打印了Person对象p,而没有调用Person中的重写方法toString(),不理解
sis.close();
}
public static void writeObj()throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "obj.txt" ) );//文件名一般不存为txt,存为.class格式
oos.writeObject( new Person( "zhangsan1", 331 ) );
oos.close();
}
}