BufferedWriter keeps erasing what I wrote

72 views Asked by At

I have the following class:

public class test{
    private static final File testfile = new File("filename")//imaginary file name
private static BufferedWriter writer = null;
    public void test1(){
      writer = new OutStreamWriter(newFileOutputStream(testfile));
      writer.write("hello");
      writer.close();
}
    public void test2(){
      writer = new OutStreamWriter(newFileOutputStream(testfile));
      writer.write("hello");
      writer.close();
}

}

I want both of them to write to the same file whenever called and I create bufferedwriters inside each of the methods. However, once i call close on to the buffered writer, it cannot be opened again. How do I avoid this so I can call both methods multiple times?

1

There are 1 answers

3
A.sharif On

I believe you had the same issue of this poster Java - Do not overwrite with bufferedwriter

Sanjay T. Sharma says:

"FileWriter takes an optional boolean argument which specifies whether it should append to or overwrite the existing content. Pass in true if you want to open the file for writing in append mode."