Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make PrintWriter overwrite old file

Tags:

java

I'm working on a project where I need to print some data to a file. During debugging phase, I would like to overwrite the old textfile so that I don't have to delete the old file just to see the result of some changes that I've made in the code. Currently, the new output data is either added to the old data in the file, or the file doesn't change at all (also, why could this be?). The following is, in essence, the printing part of the code:

public class Test {
     public static void main(String[] arg) {
     PrintWriter pw = null;
     try {
         pw = new PrintWriter(new FileOutputStream("Foo.txt", true));
     } catch (Exception e){}
     double abra = 5;
     double kadabra = 7;    
     pw.printf("%f %f \n", abra, kadabra);
     pw.close();
     }
}

Thanks!

like image 915
Alexandre Vandermonde Avatar asked Jun 08 '14 23:06

Alexandre Vandermonde


Video Answer


2 Answers

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 ).

like image 187
Neeraj Kumar Avatar answered Oct 08 '22 02:10

Neeraj Kumar


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.

like image 20
Sergey Kalinichenko Avatar answered Oct 08 '22 04:10

Sergey Kalinichenko