BufferedReader Tutorial

The BufferedReader class is used to read text from a character stream. This tutorial builds on concepts from both my InputStreamReader Tutorial and my FileReader Tutorial, I highly recommend watching them first. This tutorial will demonstrate reading text from an input stream from the keyboard and will also demonstrate reading an input stream from a text file. The BufferedReader class has the same read() method that both InputStreamReader and FileReader use to read a single byte at a time. The BufferedReader class introduces a method named readLine() which will read an entire line of text which is a huge improvement. The BufferedReader class implements AutoClosable so we can use the try-with-resources type exception handling.

String readLine()



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md BR
C:\Java>cd BR
C:\Java\BR>Notepad Example.txt

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


First line of the text file.
Second line of the text file.
Third line of the text file.
Fourth line of the text file.
Fifth line of the text file.
C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md BR
C:\Java>cd BR
C:\Java\BR>Notepad BR.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.io.*;
class BR {
    public static void main(String args[]) {
        System.out.print("Enter some text and press Enter: ");
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("You typed: " + br.readLine());
            System.out.println("\n---------\n");    
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }

       /* try (BufferedReader br = new BufferedReader(new FileReader("Example.txt"))) {
            System.out.println("The contents of Example.txt ...");
            while(br.ready()) {
                System.out.println(br.readLine());
            }
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }*/
    }
}

Now switch back to the command prompt (CMD) and type in javac BR.java and press Enter.
Now type in java BR and press Enter.


C:\Java\BR>javac BR.java
C:\Java\BR>java BR
Enter some text and press Enter:
results vary

---------

First line of the text file.
Second line of the text file.
Third line of the text file.
Fourth line of the text file.
Fifth line of the text file.

Final thoughts

The BufferedReader class comes in very handy for reading a single line of input stream from the keyboard, or the entire contents of a text file.


Tutorials