首先先定义一个user类需继承Serializable
package test;
import java.io.IOException;
import java.io.Serializable;
public class user implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
编写一个测试类,生成一个user对象,将其序列化后的字节保存在硬盘上,然后再读取被序列化后的字节,将其反序列化后输入user的name属性
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class test1 {
public static void main(String[] args) {
try {
FileOutputStream out =new FileOutputStream("d:/1.bin");
ObjectOutputStream obj_out = new ObjectOutputStream(out);
user u = new user();
u.setName("test");
obj_out.writeObject(u);
//利用readobject方法还原user对象
FileInputStream in = new FileInputStream("d:/1.bin");
ObjectInputStream ins = new ObjectInputStream(in);
user u1 = (user)ins.readObject();
System.err.println(u1.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}