Reasoning about which method BufferedWriter
overrides is pointless. All non-abstract methods of the Writer
class are implemented in terms of other methods, to finally end up at one of the abstract methods, as the Writer
itself does not implement any actual writing logic (how could it?).
Since Writer
does not have any notion of a delegation target, it’s impossible to have any method delegating to the target writer without interception by the BufferedWriter
subclass, as only that subclass knows the target. So all write
methods, as well as the append
methods, are under the BufferedWriter
’s control and will buffer, if the the data to be written is smaller than the buffer’s capacity.
That said, in your example,
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)));
bw.write(data);
bw.close();
there is no advantage in buffering, as the buffer will be flushed right in the subsequent close()
operation. So in the best case, the data
in larger than the buffer and you have just unnecessarily created a BufferedWriter
instance. But if data
is smaller than the buffer, you have also performed an unnecessary copy operation from data
to the buffer, before the data gets actually written.
For writing a single item, there is no sense in buffering. Besides that, it is quiet dangerous to offer an append
parameter that is actually ignored, pretending a functionality that is not there, especially when this can result in unintended overwriting of existing data in the target file. Further, you should use the try-with-resources construct to safely close the writer:
public static void SaveTextToFile(String fileName, String data, boolean append)
throws IOException {
try(Writer w = new FileWriter(fileName, append)) {
w.write(data);
}
}
or
// use StandardOpenOption.APPEND to append
public static void SaveTextToFile(String fileName, String data, OpenOption... o)
throws IOException {
Files.write(Paths.get(fileName),
Collections.singleton(data), Charset.defaultCharset(), o);
}
which may render your method obsolete, as it only delegates to an already existing method