Search code examples
javafilewriter

Java FileWriter refusing to overwrite


I'm very confused...

public class Testing {

    public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {

        System.out.println("Testing overwrite");

        FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false);

        writer.write("First test");
        writer.flush();

        TimeUnit.SECONDS.sleep(5);

        writer.write("Second test");
        writer.flush();

        writer.close();

    }

}

After completion, the contents of the file is:

First testSecond test

The boolean passed to the FileWriter with the value of False should be causing an overwrite, not an append, according to the Java docs here: Java 6 Filewriter API

I've had this problem in the past, and I've used a RandomAccessFile to bypass the problem, but now it's just annoying me!

Any ideas or suggestions would be greatly appreciated, thanks!


Solution

  • When calling FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false); it will overwrite the file. It won't overwrite per .write. The option only applies for the contructor.