Maxim Gotovchits
Maxim Gotovchits

Reputation: 769

Java Input stream appending without deleting

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?

Upvotes: 0

Views: 3104

Answers (2)

Maxim Gotovchits
Maxim Gotovchits

Reputation: 769

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!

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35096

Add true parameter to the FileOutputStream so that it will append

DataOutputStream stream = new DataOutputStream(new FileOutputStream("myfile.dat", true));

Upvotes: 1

Related Questions