Search code examples
javafilewriter

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)


Solution

  • Writer (of which FileWriter is a subclass) is documented to work in a stream-oriented model, vs. for instance a random access one. Consecutive writes via the same Writer instance always append. To overwrite an existing file, you need to construct a new FileWriter instance every time. It is actually a fairly cheap operation anyway.