本帖最后由 古银平 于 2012-11-25 16:36 编辑
自己定义的Person类。将Person对象放入文件1.txt中,然后从文件中读取出来,问题——显示的是com.day21.Person@10b30a7,而不是lisi 23.
public class Person implements Serializable{
public static final long serialVersionUID=42L;
private String name;
int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String ToString(){
return name+"::"+age;
}
}
public class ObjectStreamDemo {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//writerObj(); //将Person对象写入方法
readObj(); //将对象读取出的方法
}
public static void readObj() throws Exception{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("E:/1.txt"));
Person p=(Person) ois.readObject();
System.out.println(p);
ois.close();
}
public static void writerObj() throws Exception{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("E:/1.txt"));
oos.writeObject(new Person("lisi",23));
oos.close();
}
} |