stella
stella

Reputation: 2596

Why doesn't BufferedReader buffer the input?

I ran the following example:

public static void main(String[] args) throws IOException{
        Reader reader = new BufferedReader(new InputStreamReader(System.in));
        int character;
        do{
            character = reader.read();
            System.out.println(character);
        } while(character != '\n');
    }

and was actually confused by the behaviour. I thought the default buffer size of the BufferedReader is large enough to hold more than 1 character.

But, when I entered

a__NEW_LINE__

it causes the character to be printed along with new line. Why? I expected that the buffer is not full, therefore there should be no output.

Upvotes: 1

Views: 68

Answers (1)

Mehdi Javan
Mehdi Javan

Reputation: 1091

BufferedReader buffers data when possible. In this case there is no data to buffer. So, it returns what you enter immediately. BufferedReader is useful when is used with large streams such as a file (FileInputStream) and in all cases the read method returns one character while behind the scene, BufferedReader reads more data (depends on buffer size) from related InputStream and caches it to improve performance.

Upvotes: 3

Related Questions