如何在 Java 上的文件上追加对象?

How to append objects on a file on Java?

我正在尝试在 Java 上做一个应用程序,我需要在其中将 ArrayLists 保存在一个文件中。我一直在寻找如何做到这一点,我找到了下一个代码:

ArrayList<Expediente> al = new ArrayList<Expediente>();
Expediente exp = new Expediente("Expediente data");

try{
    File file = new File("Pathname");
    FileOutputStream ofs = new FileOutputStream(file);
    ObjectOutputStream oos = new ObjectOutputStream(ofs);
    oos.writeObject(al);
    oos.close();
    ofs.close();
} catch (IOException e) {
    System.err.println("Error!");
    e.printStackTrace();
}

我现在的问题是,如果我想保存相同的 ArrayList 但使用另一个数据,或者如果我重新打开文件,文件中的第一个数据将被覆盖。

有人能告诉我如何将这个新数据追加到文件中吗?

谢谢。

在 FileOutputStream 构造函数中将 append 标志设置为 true。

FileOutputStream ofs = new FileOutputStream(file, true);

http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

而不是

FileOutputStream ofs = new FileOutputStream(file);

您可以使用

FileOutputStream ofs = new FileOutputStream(file, true);

参见 Java API here