How to make PrintWriter overwrite old file

Pass false to the append parameter to overwrite the file:

pw = new PrintWriter(new FileOutputStream("Foo.txt", false));

Passing true for the second parameter indicates that you want to append to the file; passing false means that you want to overwrite the file.


Simply pass second parameter false.

Also you can use other writer object instead of FileOutputStream as you are working with txt file. e.g

pw = new PrintWriter(new FileWriter("Foo.txt", false));

or

pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));

while working with txt/docs files we should go for normal writer objects( FileWriter or BufferedWriter) and while working with binary file like .mp3 , image, pdf we should go for Streams ( FileOutputStream or OutputStreamWriter ).

Tags:

Java