Is java.io.FileWriter designed only for a single use?

I'm building a program that constantly writes to the same file, using java.io.FileWriter.

During run-time, whenever I need to update the file, I call a method that writes "properly" and uses a class-level FileWriter. The problem starts on the second .write call, when the FileWriter starts appending to the file, instead of overwriting it.

public class Example {
    private FileWriter fw = new FileWriter("file's path", false);

    public void writeToFile(String output) {
        fw.write(output);
        fw.flush();
    }
}

I'm suspecting that somehow the FileWriter's "memory" keeps its previously written data, but I don't want to close and initialize it for every call, as it seems wasteful.

  1. Do I even need the .flush call after each .write call?
  2. Do I have another option but initializing the FileWriter and .close-ing it on every call?

(I tried looking in older questions, but they all seem to deal with FileWriters that won't append, or theoretical FileWriter.flush interpretations)

Jon Skeet
people
quotationmark

The problem starts on the second .write call, when the FileWriter starts appending to the file, instead of overwriting it.

Yes, you've got an open writer. Writing to that writer will just write additional text to the file - just like multiple calls to write on an OutputStream will write additional data to the stream rather than overwriting existing data on each call. Imagine if your code had:

fw.write("first");
fw.flush();
fw.write("second");
fw.flush();

Would you expect that to replace the entire content of the file with "second"? I wouldn't - and that's exactly what happens if you call writeToFile twice.

If you want every call to writeToFile to completely replace the content of the file, you should create a new writer, write, then close the writer, within the method.

Personally I'd avoid using FileWriter anyway as it writes using the platform-default encoding, which isn't great.

I'd use either Files.write which will write a sequence of lines to a file, or Files.newBufferedWriter to create a writer for multiple write calls.

people

See more on this question at Stackoverflow