Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the difference between using a BufferedWriter or writing straight to file? [duplicate]

Possible Duplicate:
In Java, what is the advantage of using BufferedWriter to append to a file?

The site that I am looking at says

"The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings."

What make's it more efficient and why?

like image 277
Slerig Avatar asked Dec 17 '22 07:12

Slerig


2 Answers

BufferedWriter is more efficient because it uses buffers rather than writing character by character. So it reduces I/O operations of the disk. Data is collected in a buffer and write to the file when the buffer is full. This is why sometimes no data is written in the file if you didn't call flush method. That is data is collected in the buffer but program exits before writing them to the file. Calling flush method will cause the data to be written in the file even the buffer is not filled completely.

like image 121
Krishan Avatar answered Feb 22 '23 23:02

Krishan


The cost of writing becomes expensive when you write character by character to the file. For reducing that cost, buffers are provided. If you are writing to Buffer, it waits for some limit and then writes the whole to the disk.

like image 30
Naved Avatar answered Feb 23 '23 00:02

Naved