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.
FileWriter is a specialized OutputStreamWriter for writing character files. It doesn't expose any new operations but works with the operations inherited from the OutputStreamWriter and Writer classes. Until Java 11, the FileWriter worked with the default character encoding and default byte buffer size.
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java. Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
FileWriter writes streams of characters while FileOutputStream is meant for writing streams of raw bytes. FileWriter deals with the character of 16 bits while on the other hand, FileOutputStream deals with 8-bit bytes.
When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With