7

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rollerball
  • 12,618
  • 23
  • 92
  • 161

2 Answers2

1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1

I would recomand to always use a BufferedWriter. It allows you to control the actual buffer size and you can guarantee that regardless of the JVM you use, IO will be buffered which brings a huge IO performance boost.

morpheus05
  • 4,772
  • 2
  • 32
  • 47
  • Ok but what about FileWriter is it Buffered? It has only this famous standard byte-buffer? How does it work? is the JVM who handles it? – Rollerball Jul 27 '13 at 15:57
  • A look in the JDK 1.7 Code showed a writeBuffer in the Writer Baseclass. So all writers have this buffer. The BufferedWriter uses a second buffer private char cb[]; This leads to the conclusion that this hidden buffer may not be part in all JDK implementations (what about android ?) – morpheus05 Jul 27 '13 at 15:59
  • 2
    No. The write method is overridden in OutputStreamWriter. The buffering is happening in the StreamEncoder used by OutputStreamWriter, which encodes characters to bytes. – JB Nizet Jul 27 '13 at 16:03
  • You right, OutputStreamWriter overrides most of the write methods and circumvent the buffer in the baseclass. – morpheus05 Jul 27 '13 at 16:09