Java 使用ObjectInputStream将对象存储到arraylist时遇到问题
好的,我刚刚更改了我的代码,在while循环中使用true。现在,当它从文件中读取时,我得到一个流损坏的异常。这可能是因为奥宾不是新来的 私有类viewStudentListener实现ActionListener { 已执行的公共无效操作(操作事件e) {Java 使用ObjectInputStream将对象存储到arraylist时遇到问题,java,deserialization,objectinputstream,Java,Deserialization,Objectinputstream,好的,我刚刚更改了我的代码,在while循环中使用true。现在,当它从文件中读取时,我得到一个流损坏的异常。这可能是因为奥宾不是新来的 私有类viewStudentListener实现ActionListener { 已执行的公共无效操作(操作事件e) { 试一试{ ArrayList<Student> students = new ArrayList<Student>(); FileInputStrea
试一试{
ArrayList<Student> students = new ArrayList<Student>();
FileInputStream fin = new FileInputStream("Students.bin");
ObjectInputStream obin = new ObjectInputStream(fin);
int id = Integer.parseInt(ID.getText());
int count = 0;
while(true)
{
try{
Student s = (Student) obin.readObject();
students.add(s);
}
catch(EOFException eofException){
break;
}
}
while (count < students.size())
{
if(students.get(count).equals(id))
{
fName.setText(students.get(count).getFirstName());
lName.setText(students.get(count).getLastName());
}
count++;
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}available()>0
不是流结束的有效测试。请参阅Javadoc
读取流的正确方法是通过
while(true)
直到抛出EOFEException
为止。您的for循环是较新的结束循环不是在结束时抛出文件结束异常吗?只需序列化学生数组列表或其他内容,然后读取一个序列化的对象,您可能会省去很多麻烦。您是如何编写此文件的?
private class createNewStudentListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
Student s = new Student(enterFirstName.getText(), enterLastName.getText());
File newStudent;
newStudent = new File("Students.bin");
FileOutputStream outStream = new FileOutputStream("Students.bin", newStudent.exists());
ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream);
objectOutputFile.writeObject(s);
JOptionPane.showMessageDialog(null, "The new student was added successfully");
String id = Integer.toString(s.getID());
IDNUM.setText(id);
s = null;
objectOutputFile.close();
}
catch (emptyString a)
{
JOptionPane.showMessageDialog(null, a.getMessage());
} catch (Exception a) {
JOptionPane.showMessageDialog(null, a.getMessage());
}
}
}