In Java, what is the difference between using BufferedWriter or writing directly to a file?

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

The site I'm looking at says

"The BufferWriter class is used to write text to a character output stream, to buffer characters to ensure that individual characters, arrays, and strings are efficiently written."

What makes it more effective and why?

+4
source share
5 answers

BufferedWriter waits until the buffer (8192 bytes) is full and writes the entire buffer in a single disk operation. Unbuffered every single entry will result in discrete I / O, which is obviously more expensive.

+3
source

BufferedWriter more efficient because it uses buffers instead of writing character by character. Thus, it reduces disk I/O Data is collected in the buffer and written to the file when the buffer is full. This is why sometimes files are not written to the file if you did not call the flush method. That is, data is collected in a buffer, but the program exits before writing it to a file. Calling flush will cause the data to be written to the file, even if the buffer is not full.

+5
source

The cost of writing becomes expensive when you write character by character to a file. Buffers are provided to reduce this cost. If you write a buffer, it waits for some limit and then writes the integer to disk.

+4
source

As the name suggests, BufferedWriter uses a buffer to reduce recording costs. If you are writing a file, you may know that a 1 byte record or a 4 kbyte record is approximately the same. The time required to perform such a recording is mainly determined by the access time (~ 8 ms), which is the time required to rotate the disk and to search for the desired sector.

In addition, the aggregation of small records in a larger volume can reduce the operating system overhead, providing better performance.

Most operating systems have an internal buffer for caching entries. However, these caches try to figure out what the application does by analyzing write patterns. If the application itself can perform this caching and write only when the data is ready, the result (in terms of performance) is better.

0
source

The hard disk has a minimum unit of information storage, for example, if you write one byte, the operating system asks the disk to store the storage unit (I think the minimum is 512 bytes). Therefore you ask to write one byte, and the operating system writes much more. If you ask to store 512 bytes with 512 calls, you end up doing a lot more I / O (512 disk operations) that buffer 512 bytes and only give one call (1 disk operation).

0
source

Source: https://habr.com/ru/post/1382650/


All Articles