ObjectOutputStream obs=null;
Person person=null;
try {
obs=new ObjectOutputStream(new FileOutputStream("F:\\Javax学习\\s.txt"));
person=new Person("张三", 21, 95001);
obs.writeObject(person.toString());
obs.flush();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
ObjectInputStream obi=null;
try {
obi=new ObjectInputStream(new FileInputStream("F:\\Javax学习\\s.txt"));
String str=obi.readObject().toString();
if(str!=null)
System.out.println("名字:"+person.getName()+";身份证:"+person.getIdCard());
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}}
class Person implements Serializable{
private String name;
private int age;
private int idCard;
Person(String name,int age,int idcard){
this.name=name;
this.age=age;
this.idCard=idcard;
}
@Override
public String toString() {
return this.name+this.idCard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdCard() {
return idCard;
}
public void setIdCard(int idCard) {
this.idCard = idCard;
}执行完程序以后查看文本文件显示乱码,但是执行反序列化后可以正常输出:
名字:张三;身份证:95001
问题来了:能不能用文本文件查看内容?(Ps:新手学Java,如有错误请多指教)
class文件也是一堆十六进制,用文本编辑器打开看也是各种乱码。
应修改为:
obs.writeObject(person);
同样:
String str=obi.readObject().toString();
应修改为:
person=(Person)obi.readObject();