0

How can I append data in file without making it clean after FileInputStream(...)?

That's how I append from my HashMap <String, String> storage:

DataOutputStream stream = new DataOutputStream(new FileOutputStream("myfile.dat"));
    for (Map.Entry<String, String> entry : storage.entrySet()) {
        byte[] bytesKey = entry.getKey().getBytes("UTF-8"); //I need to write using UTF8
        stream.writeInt(bytesKey.length);
        stream.write(bytesKey);
        byte[] bytesVal = entry.getValue().getBytes("UTF-8");
        stream.write(bytesVal);
    }
    stream.close();

So, the problem is when I turn it on again it clears all the previous data in my file. How to avoid that?

Maxim Gotovchits
  • 729
  • 3
  • 11
  • 22
  • 1
    possible duplicate of [How to append text to an existing file in Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Mike G Oct 09 '14 at 15:39
  • http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean) – Mike G Oct 09 '14 at 15:39

2 Answers2

1

Add true parameter to the FileOutputStream so that it will append

DataOutputStream stream = new DataOutputStream(new FileOutputStream("myfile.dat", true));
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • No, the problem is when I turn my program on again it clears all the previous data in my file. How to avoid that? Flag `true` doesn't solve this problem – Maxim Gotovchits Oct 09 '14 at 16:14
  • You solve this by constructing the FileOutputStream the way I have explained so that it starts in append mode – ControlAltDel Oct 09 '14 at 16:21
  • Look: 1) I start program 2) Write data in my file 3) Terminate program 4) Open file and I see all the data I wrote 5) Start program again 6) Write smth again 7) Terminate 8) Look at file, BUT there's no data that I wrote the first time. There's only the last data I appended last time. That's the problem – Maxim Gotovchits Oct 09 '14 at 16:24
  • I'm sorry. It's so bad that it's forbidden to say bad words here, I'm so scattered. The problem was that one of my 8 functions called PrintWriter so it cleared all data... Thank You! =) – Maxim Gotovchits Oct 09 '14 at 16:49
1

Everyone who see this answer, please, be as attentive as possible. I spent whole day to solve this problem just beacuse one of my classes called PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("myfilename", "UTF8")); so this cleared my file.

Good luck!

Maxim Gotovchits
  • 729
  • 3
  • 11
  • 22