How to add data to a file using BufferedWriter and FileOutPutStream

advertisements

This question already has an answer here:

  • How to write data with FileOutputStream without losing old data? 3 answers

In the below code I am trying to append some text to a file using FileOutputStream and BufferedWriter as shown below.At ru time, despite the file has some data, when i use FileOutputStream and BufferedWriter i found the file is empty and even the data i want to append bw.write("new information"); is not existing the file is completely empty.

Kindly please let me know how to fix it.

Code:

File f = new File(SystemConfig.getSystConfigInstance("E"));
    System.out.println(f.getAbsolutePath() + " name: " + f.getName());

    OutputStream os = new FileOutputStream(f);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
    bw.write("new information");


Try this, FileOutputStream(File file, boolean append) with append

OutputStream os = new FileOutputStream(f, true);

If the append boolean is true which means it will append the new content with the old content.

instead of

OutputStream os = new FileOutputStream(f);

FileOutputStream has the default append method also. So use this to append the content with the old one.