Does FileWriter use a buffer? (it acts as in my example)


I am using FileWriter and I have noticed strange behavior. I buffer my collection myself and each x lines that I use

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

It does not write to a file. I continue to call it a few more lines, and only after it is completely full does it write the file.
Does it use a buffer? I can not find it in the documentation.

+6
java filewriter
source share
4 answers

The second sentence, an overview of the FileWriter class, says:

The constructors of this class assume that the default character encoding and byte size are acceptable by default . To determine these values โ€‹โ€‹yourself, create an OutputStreamWriter in FileOutputStream.

(My emphasis)

It is so clear that it is buffered (if the default byte size is not equal to zero by default, and they are very strange with their wording).

I suspect that I just used OutputStreamWriter on FileOutputStream . Looking at OutputStreamWriter :

Each call to the write () method forces the encoder to be converted to the specified character (s). The resulting bytes are accumulated in the buffer before being written to the base output stream.

(My emphasis)

If you want different buffers at different levels to be flushed as far as you can, look at the flush method.

+12
source share

I suspect this is an implementation detail, but I would expect most implementations to use a buffer, yes. Of course, you should not rely on the fact that it is not buffered. When you hide or close a record, that should be fine.

Note that I personally do not like to use FileWriter , because it does not allow you to specify a character encoding - instead, I usually wrap FileOutputStream in OutputStreamWriter .

+5
source share

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

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

0
source share

It seems to be using a buffer, but in some other way (the low-level buffer may be empty by default). Need to wrap it with 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>" 
0
source share

All Articles