![](/img/trans.png)
[英]How do I write multiple objects to the serializable file and read them when the program is used again?
[英]Write Multiple objects in a File and Read them
我正在尝试使用用户界面创建一个简单的程序。 来自gui的用户插入Person Implements Serializable类的名称,姓氏和年龄。
一切都很好,但只有一个人,第一个人! 似乎每次我将新对象发送到我的文件时,它确实被写入文件,因为文件大小越来越大。
问题是当我用对象读取文件时它只返回一个,我希望返回存储在myFile中的所有类人物对象。
以下是我的代码的预览:
写对象按钮:
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
}
感谢您的任何信息!
每次打开文件时,都会向其写入标头。 当输入流阅读器在第一次读取后看到此标头时,它会抛出异常。 由于您的异常处理中没有任何“printStackTrace”调用,因此您没有看到该错误。
修复是为了防止在打开流时在后续调用中写入标头。 通过在打开文件之前检查文件是否存在来执行此操作,如果文件已经存在,请使用不写标头的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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.