Skip to content
Advertisement

How to make PrintWriter overwrite old file

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!

Advertisement

Answer

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.

Advertisement