What is the buffer size in BufferedReader?
Asked Answered
S

3

28

What is the sense of buffer size in the constructor?

BufferedReader(Reader in, int size)

As i have written the program:

import java.io.*;
class bufferedReaderEx{
    public static void main(String args[]){
        InputStreamReader isr = null;
        BufferedReader br = null;
            try{
                isr = new InputStreamReader(System.in);
//              System.out.println("Write data: ");
//              int i = isr.read();
//              System.out.println("Data read is: " + i);
                //Thus the InputStreamReader is useful for reading the character from the stream
                System.out.println("Enter the data to be read by the bufferedReader: ");
                //here isr is containing the lnefeed already so this is needed to be flushed.
                br = new BufferedReader(isr, 2);
                String str = br.readLine();
                System.out.println("The data is : :" +  str);
            }catch(IOException e){
                System.out.println("Can't read: " + e.getMessage());
            }
    }
}

Output:

Enter the data to be read by the bufferedReader: Hello world and hello world again
The data is: Hello world and hello world again

Then what does the buffer size means as i intended that it would be reading only two characters. but it was not that.

Spoofery answered 9/1, 2011 at 11:54 Comment(0)
A
38

BufferedReader buffers the input, just as the name says. This means that it reads from the input source into a buffer before passing it onto you. The buffer size here refers to the number of bytes it buffers.

Reading input from most sources is very slow. A buffer of just 2 bytes is going to hurt performance, as your program is very likely going to be waiting on input most of the time. With a buffer size of 2, a read of 100 bytes will result in reading 2 bytes from the in-memory buffer (very fast), filling the buffer (very slow), reading 2 bytes from the buffer (very fast), filling the buffer (very slow), etc - overall very slow. With a buffer size of 100, a read of 100 bytes will result in reading 100 bytes from the in-memory buffer (very fast) - overall very fast. This is assuming the buffer is contains the 100 bytes when reading though, which in a case like yours is a reasonable assumption to make.

Unless you know what you're doing, you should use the default buffer size which is quite large. One reason for a smaller buffer is when you are running on a limited-memory device, as the buffer consumes memory.

Attu answered 9/1, 2011 at 11:58 Comment(6)
then what is significance of buffer size. would you please explain?Spoofery
@codeonnitrix Added a bit of an explanation. Let me know if that's sufficient.Attu
Isn't the size the number of characters buffered instead of bytes?Eurypterid
Logcat says: Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required. What is the right way?Afterbirth
Using FileInputStream, doesn't buffer size directly influence the count of system calls to read from that file ? Like totalFileSize / bufferSize = number of system calls ? So that if you are reading a huge file line by line, then it would make sense setting bufferSize to a higher value so that it makes less system calls.. Just thinking, I can't tell from the source code, wdyt ?Sato
So, according to what you say, if I always define the size of buffer according to the size of file, like byte[] buffer = new byte[inputstream.available()], it would be the fastest, right? But, instead of finding ppl implementing this way, what we often see is using a buffer of default size or 2048 or 1024.Reliquary
R
14

http://www.docjar.com/html/api/java/io/BufferedReader.java.html

As per this java documentation, default buffer size is 8192 characters capacity. Line size is considered as 80 chars capacity.

8192 buffer size is sufficient for smaller file sizes. But again this is growable. if file contains more than 8192 characters, then fill method of bufferedreader will increase the buffer size before reading content from file. For bigger content files preferably set your own max size to buffer while creating buffered reader through constructor, so that you can avoid recreating memory and copying the old array into newly created array.

Riojas answered 23/6, 2015 at 8:11 Comment(3)
Straight forward and clearcut info.Thanks@RiojasEnrollment
The buffer actually never grows. It is of constant size. It is used just as an intermediate in-memory storage when reading from a file. I'm lazy to explain more, so look at this: https://mcmap.net/q/116697/-what-does-it-mean-by-bufferPatristic
@Patristic Upvoted for the link, but in Java BufferedReader, the buffer size can be configured in the constructor, like new BufferedReader(Reader, size) so that you can decide the size of buffer, no? Although the default size of 8192 usually is enough and suits well.Reliquary
V
10

When you read or write in a file, you must access the kernel, which actually gains access to the file. All file operations must go through the kernel. This is a fairly costly operation. Buffering causes a chunk of bytes to be read; these are held in a temporary location in RAM and are bytes are read in from this location. In this way, you are not making frequent requests of the kernel to do file IO.

If you use a huge buffer size, you will hog up RAM needlessly. If you use a tiny one, you will be bugging the kernel constantly for file requests. It is best to allow the default to be used. You can specify buffer size and experiment. Most machines will read a sector at a time or an integer number of sectors. The sector size depends upon how you format your machine.

The following experiment is interesting. Make a file with 1,000,000 zeroes in it. Use your OS's timing feature to see how fast it copies it to another file (you will write a copy program with buffered and unbuffered IO). Time it with various buffer sizes including the default.

Vichyssoise answered 30/5, 2011 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.