51,397
社区成员




private void addStudent() throws IOException {//添加学生信息
Person person = new Person();//创建学生类对象
FileOutputStream fos = new FileOutputStream("whr\\src\\dormitory\\学生信息.txt",true);
System.out.println("请按 姓名 学号 年龄 性别 的格式输入学生信息:");
person.setName(sc.next());//将输入的姓名存到对象中
person.setStudentId(sc.nextInt());//将输入的学号存入到对象中
person.setAge(sc.nextInt());//将输入的年龄存入到对象中
person.setSex(sc.next());//将输入的性别存入到对象中
person.setRoom(-1);//先都分配0号宿舍
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);//将对象存入文件中
oos.close();
}
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
异常,如图:只出现了一个对象:public class test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("whr\\src\\dormitory\\学生信息.txt");
// FileOutputStream fos = new FileOutputStream("whr\\src\\dormitory\\学生信息.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person person = (Person)ois.readObject();//遍历反序列化中的所有对象
while (person != null){
System.out.println(person.getName()+person.getStudentId()+person.getSex()+person.getRoom());
person = (Person)ois.readObject();
}
ois.close();
}
}