0

I'm trying to do an app on Java in which I need to save ArrayLists on a file. I was looking for how to do this and I found the next code:

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();
}

My problem now is that if I want to save the same ArrayList but with another data or if I reopen the file, the first data that is in the file is overwritten.

Could someone tell how to append this new data on the file?

Thank you.

Seatigh
  • 13
  • 2
  • Did you take a look at the Java API docs? – Sleafar Jul 24 '15 at 21:19
  • I think this is duplicate to this. There is good answer there. http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – ap0calypt1c Jul 24 '15 at 21:21
  • Yeah, I know about the FileWriter and the PrintWriter, but I need to write Objects, not Strings. But thank you anyway :) – Seatigh Jul 27 '15 at 12:05

2 Answers2

5

Set the append flag to true in the FileOutputStream ctor.

FileOutputStream ofs = new FileOutputStream(file, true);

See

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

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • Thank you very much :) I didn't though about this option :s hahaha – Seatigh Jul 25 '15 at 16:31
  • You're welcome. And I don't blame you -- I've been a Java programmer for 20 years, was a Java architect for Sun, wrote a lot of the certification exam questions and reviewed them all -- and I just habitually go read the API docs *any* time I'm doing Java. There are just too many details to remember. – Charlie Martin Jul 26 '15 at 00:24
1

Instead of

FileOutputStream ofs = new FileOutputStream(file);

You can use

FileOutputStream ofs = new FileOutputStream(file, true);

See the Java API here.

Aiken
  • 88
  • 5