日期:2014-05-20 浏览次数:21019 次
public class ObjectOutputStreamTest {
public static void main(String[] args) throws FileNotFoundException,
IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"hello.txt"));
Student s = new Student("安安", 20);
oos.writeObject(s);
oos.flush();
oos.close();
// 反序列化
try {
// 实例化对象输入流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"hello.txt"));
try {
// 反序列化对象
Student stu = (Student) ois.readObject();
System.out.println("学生姓名:" + stu.getName());
System.out.println("学生年龄:" + stu.getAge());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable{
private String name;
private int age;
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}