已经有一个文件,想把类序列化到文件中,然后再从文件中反序列化,怎么实现呢?
//创建一个可序列化类Person
import java.io.Serializable;
public class Person implements Serializable{
private String name;
private String sex;
public Person(String name,String sex){
this.name=name;
this.sex=sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
//测试类
public class TestDemo {
public static void main(String[] args) {
//创建一个对象
Person people = new Person("张三","男");
try {
//实例化ObjectOutputStream对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\person.txt"));
//将对象写入文件
oos.writeObject(people);
oos.flush();
oos.close();
//实例化ObjectInputStream对象
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("C:\\person.txt"));
try {
//读取对象people,反序列化
Person p = (Person)ois.readObject();
System.out.println("姓名:"+p.getName());
System.out.println("性别:"+p.getSex());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//如果可以楼主不要忘了给分
如有疑问请联系
:idea: 楼上说的对。