java - Does FileWriter use a buffer? (it acts like it does in my example)
Asked Answered
T

4

7


I am using FileWriter and I have noticed strange behavior. I buffer my collection myself and every x rows I use

 IOUtils.writelines(myList,"\n", writer );

It doesnt write to the file. I continue to call it with more lines and only after it is very full it writes to the file.
Does it use a buffer? I cant find it in its documentation.

Trestle answered 24/5, 2011 at 9:1 Comment(0)
D
12

The second sentence of the FileWriter class overview says:

The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

(My emphasis)

So clearly it's buffered (unless the default byte-buffer size is zero and they're being really odd with their phrasing).

I suspect it's just using an OutputStreamWriter on a FileOutputStream. Looking at OutputStreamWriter:

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.

(My emphasis)

If you want to ensure that various buffers at various levels are flushed, to the extent you can, look at using the flush method.

Desirae answered 24/5, 2011 at 9:6 Comment(3)
Thanks for the elaborated answer.Trestle
@user: No worries, hope that helped.Desirae
Thanks for pointing this out. I also missed it in the docs and was really confused when tail was not showing my writes!Ordovician
I
5

I suspect it's an implementation detail, but I would expect most implementations to use a buffer, yes. You certainly shouldn't rely on it being unbuffered. When you flush or close the writer, it should be fine.

Note that personally I dislike using FileWriter as it doesn't allow you to specify the character encoding - I would typically wrap a FileOutputStream in an OutputStreamWriter instead.

Interdenominational answered 24/5, 2011 at 9:5 Comment(0)
S
1

Seems that it uses buffer but in some other way (low-level, buffer could be empty by default). Need to wrap it by BufferedWriter. From BufferedWriter javadoc:

"In general, a Writer sends its output immediately to the underlying
 character or byte stream.  Unless prompt output is required, it is advisable
 to wrap a BufferedWriter around any Writer whose write() operations may be
  costly, such as FileWriters and OutputStreamWriters.  For example,

  <pre>
  PrintWriter out
    = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
  </pre>"
Swept answered 7/8, 2013 at 13:7 Comment(0)
C
0

Look at the class sun.nio.cs.StreamEncoder.CharsetSE.implWrite(). It uses a ByteBuffer.

The class StreamEncoder.CharsetSE is internally used by OutputStreamWriter which inturn is internally used by FileWriter.

Capua answered 24/5, 2011 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.