Java BufferedReader examples

Java file FAQ: Can you share some examples of the Java BufferedReader class?

Sure. When it comes to reading character input streams, the Java BufferedReader class is extremely important, and I'll demonstrate this in several different source code examples.

Using a Java BufferedReader with a FileReader

I'll start with what might be the most common use of the BufferedReader class, using it with a FileReader to read a text file. (This code comes from my earlier "How to open and read a file with Java" tutorial.)

The following method demonstrates my usual Java file-reading approach, including the Java 5 syntax:

private List<String> readFile(String filename)
throws Exception
{
    String line = null;
    List<String> records = new ArrayList<String>();

    // wrap a BufferedReader around FileReader
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

    // use the readLine method of the BufferedReader to read one line at a time.
    // the readLine method returns null when there is nothing else to read.
    while ((line = bufferedReader.readLine()) != null)
    {
        records.add(line);
    }
  
    // close the BufferedReader when we're done
    bufferedReader.close();
    return records;
}

Again, this is the usual approach I take with Java to read a text file from a filesystem. I start with a FileReader, so it's important to understand how that class works. As the FileReader javadoc states:

The FileReader ... is a convenience class for reading character files ... FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

Why both BufferedReader and FileReader?

I wrap a BufferedReader around the FileReader for two reasons. First, the BufferedReader does what its name implies, buffering the input to make the reading process much faster. Second, the BufferedReader provides a readLine method which converts each line of input into a Java String, and greatly simplifies the file-reading process, as you saw in that previous example.

Regarding the buffering process, here are a few lines from the BufferedReader javadoc:

The BufferedReader ... reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.

It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Before I leave this example, I should also restate a line I included in the documentation above:

The BufferedReader readLine method returns null when there is nothing else to read.

Because of that behavior, it's very common to write a while loop that iterates over a BufferedReader as shown in the example above, and again here:

while ((line = bufferedReader.readLine()) != null)

Again, the BufferedReader readLine method either returns a String or a null reference, and it's a great convenience method to use when reading text input like this.

Using a BufferedReader with System.in and an InputStreamReader

It's also common to use the Java BufferedReader with an InputStreamReader. We saw this mentioned in the BufferedReader javadoc statement above, and now I'll share an example where I wrap a BufferedReader around an InputStreamReader to read from System.in.

The following code comes from my "How to read command-line input with Java" tutorial. I've simplified that code and added some documentation to it so you can see how to wrap a BufferedReader around an InputStreamReader (which in turn is already wrapped around System.in):

import java.io.*;

public class JavaBufferedReaderSystemInExample
{
    public static void main (String[] args) 
    throws Exception
    {
        String userName = null;

        //  prompt the user to enter their name
        System.out.print("Enter your name: ");

        //  open up standard input, and buffer it
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        // use the readLine method of the BufferedReader class
        // to get whatever line the user types in:
        userName = bufferedReader.readLine();
        System.out.println("Thanks for the name, " + userName);
    }
}

I hope the comments in the code cover what I'm doing in this code, but if you'd like more information, please visit my "How to read command line input with Java" tutorial.

Using a Java BufferedReader with a URLConnection

As one final BufferedReader example, the following code snippet again shows how to wrap a BufferedReader around an InputStreamReader, but in this case the InputStreamReader is wrapped around the input stream from a Java URLConnection:

URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

String line;
while ((line = bufferedReader.readLine()) != null)
{
    content.append(line + "\n");
}
bufferedReader.close();

As you can see, once you wrap a BufferedReader around an InputStreamReader, the rest of our code is very similar. As mentioned earlier, I usually just try to get to a point where I can use the BufferedReader readLine method. I think of that as a convenience method that makes reading from a file, standard input, or an internet connection (URL or socket) much easier.

If you're interested in more details on this last BufferedReader example, I took that code snippet from my "How to open and read content from a URL with Java" tutorial, and there's much more discussion in that tutorial.

Java BufferedReader summary

As you've seen, the common thread around all of these examples is wrapping a BufferedReader around an InputStream, and then using the BufferedReader readLine method to simplify the process of reading the input as a series of Strings.

Although I haven't discussed it in great length, the BufferedReader does what its name implies, buffering the input to make reading much faster. In tests I conducted before the Java 5 days, using a BufferedReader made file reading at least ten times faster than using a non-buffered approach.

For more information on the Java BufferedReader class, please visit the BufferedReader javadoc link shown above, or the links to any of my other BufferedReader-related tutorials shared above.

Post new comment

The content of this field is kept private and will not be shown publicly.