我正在尝试创建一个带有用户界面的简单程序。来自 gui 的用户插入类 Person Implements Serializable 的名字、姓氏和年龄。
一切正常,但只适用于一个人,第一个人!似乎每次我向我的文件发送一个新对象时,它确实被写入了文件,因为文件大小越来越大。
问题是,当我读取包含对象的文件时,它只返回一个,我希望返回存储在 myFile 中的类 person 的所有对象。
先看一下我的代码:
写对象按钮:
try {
per = new Person(name, sur, age);
FileOutputStream fos = new FileOutputStream("myFile", true);
ObjectOutputStream oos;
oos = new ObjectOutputStream(fos);
oos.writeObject(per);
oos.flush();
oos.close();
//some other code here
} catch (IOException e) {
//some code here
}
读取对象按钮:
try {
FileInputStream fis = new FileInputStream("myFile");
ObjectInputStream ois;
ois = new ObjectInputStream(fis);
try {
rper = (Person) ois.readObject();
ois.close();
JOptionPane.showMessageDialog(null, "People:" + rper, "Saved Persons", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException e) {
//some code here
}
} catch (IOException e) {
//some code here
}
感谢您提供任何信息!
最佳答案
每次打开文件时,都会向其中写入一个标题。当输入流读取器在第一次读取后看到此 header 时,它会抛出异常。由于您在异常处理中没有任何“printStackTrace”调用,因此您没有看到该错误。
修复是为了防止在打开流时在后续调用中写入 header 。通过在打开文件之前检查文件是否存在来执行此操作,如果它已经存在,则使用不写入 header 的 ObjectOuputStream 的子类。
boolean exists = new File("myFile").exists();
FileOutputStream fos = new FileOutputStream("myFile", true);
ObjectOutputStream oos = exists ?
new ObjectOutputStream(fos) {
protected void writeStreamHeader() throws IOException {
reset();
}
}:new ObjectOutputStream(fos);
然后您可以使用单个对象输入流读取所有记录...
FileInputStream fis = new FileInputStream("myFile");
ObjectInputStream ois = new ObjectInputStream(fis);
while(fis.available() > 0) {
try {
Object rper = ois.readObject();
JOptionPane.showMessageDialog(null, "People:" + rper, "Saved Persons", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
ois.close();
关于java - 在文件中写入多个对象并读取它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22113310/