序列化与反序列化

来源:互联网 发布:女程序员的职业规划 编辑:程序博客网 时间:2024/06/16 05:54

//实体类实现Serializable 接口
public class Worker implements Serializable {

private String name;
private String passwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}

}
//序列化将对象写入文件
 try 
{
        File file = new File("E:\\info.txt");
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(worker);
        oos.close();

catch (IOException e)
{
        e.printStackTrace();
}
//反序列化读取文件
 try 
{
        File file = new File("E:\\info.txt");
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois=new ObjectInputStream(fis);
        worker=(Worker) ois.readObject();
        ois.close();

catch (FileNotFoundException e)
{
        e.printStackTrace();
}
catch (IOException e)
{
        e.printStackTrace();
}
catch (ClassNotFoundException e)
{
        e.printStackTrace();
}