读书人

怎样写一个类描述学生并将几个学生的

发布时间: 2012-02-22 19:36:55 作者: rapoo

怎样写一个类描述学生,并将几个学生的信息能序列化到文件中保存,并能再次读出来?
怎样写一个类描述学生,并将几个学生的信息能序列化到文件中保存,并能再次读出来?

[解决办法]
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Student s1 = new Student( "Tom ", 18);
Student s2 = new Student( "Jerry ", 19);

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( "aa.txt "));
oos.writeObject(s1);
oos.writeObject(s2);
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream( "aa.txt "));
Student sa1 = (Student)ois.readObject();
Student sa2 = (Student)ois.readObject();
ois.close();
System.out.println(sa1.getName() + "\t " + sa1.getAge());
System.out.println(sa2.getName() + "\t " + sa1.getAge());
}

Student 类需要实现 java.io.Serializable 。

不知道是这个意思吗?

读书人网 >J2SE开发

热点推荐