Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is FileWriter buffered?

Tags:

java

io

buffer

I would like to know whether or not FileWriter is buffered.

In this SO question, it seems that it is, however in this SO question it seems that is not (it would be a system call for each time write(..) gets called).

So, basically, reading those two Q&A, I am a little confused. Is anybody able to clearly explain it out?

EDIT: Problem solved by reading this API of which I am quoting the relevant part:

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

Since FileWriter extends OutputStreamWriter, it applies to it as well.

Thanks for your time though, I am aware I asked something quite specific.

like image 997
Rollerball Avatar asked Aug 22 '26 02:08

Rollerball


1 Answers

In fact, a FileWriter does have internal buffering. The buffer is a ByteBuffer (with default size 8192 bytes). You can find it in the sun.io.cs.StreamEncoder object that OutputStreamWriter uses to encode characters to the chosen character set / encoding.

I looked at the Java 17 OpenJDK source code to determine this. It is an implementation detail, and could vary depending on Java version ... and vendor.

like image 176
Stephen C Avatar answered Aug 23 '26 17:08

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!