java. io. Is filewriter designed for one-time use only?

I'm using Java io. Filewriter builds a program that keeps writing to the same file

During runtime, whenever I need to update a file, I call a method, writes "properly", and use class level filewriter When filewriter starts appending to a file instead of overwriting it, the problem starts the second time The write call begins

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

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

I suspect that filewriter's "memory" retains previously written data, but I don't want to close and initialize it for each call because it seems wasteful

>Every time I even need it after the write call Flush call? > Do I have other options, but initialize filewriter and close it on every call?

(I try to look at older problems, but they all seem to deal with filewriters that will not be attached, or the theoretical explanation of filewriter. Flush)

Solution

Writer (where filewriter is a subclass) is documented and works in a flow oriented model, not, for example, a random access model Continuous writes through the same writer instance are always appended To overwrite an existing file, you need to construct a new filewriter instance each time Anyway, it's actually a fairly cheap operation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>