BufferedReader

Java BufferedReader Example

In this example we are going to talk about BufferedReader Java class. BufferedReader is a subclass of Reader class. As you might know, Reader is a utility class for reading character streams. Such a stream could be obtained from a text file, from the console , from a socket, from a pipe , from a database or even from a memory location. Any resource that represents a sink of characters can be read with a sub class of the Reader class. For example if that sink of characters is a text file, you can easily obtain such a Reader using FileReader class.

But in general, most helper classes that connect your program with an input source, offer a method that help you grab an InputStream connected to that source, so that you can read data from it and make them available for manipulation from inside your program. For example Socket class offers a getInputStream() method for that purpose. As you know, InputStream‘s job is to read streams of bytes. Then, you can wrap that InputStream around a Reader class to bridge the byte stream to a character stream. In general, that reader is the InputStreamReader class. Using InputStreamReader you can read sequences of characters from a character stream. What this class simply does is to encode the bytes it reads to a specified character set encoding, like UTF-8.

Using an InputStreamReader to read sequences of characters into a char[] array is usually good enough. But this is not the case for I/O intensive applications. The thing is that InputStreamReader‘s read() method is not implemented in the most efficient way possible. Every time the read() method of InputStreamReader is invoked, it reads one byte from the byte stream and encodes it. If the character set requires the character to be presented in more than one bytes, then the reader has to read one more byte and encode both bytes. If you request to read 1000 characters this procedure will be repeated 1000 times, invoking a new read() call every time.

As you can imagine this can be a real performance bottleneck. In this situations, the simplest solution one can follow, is buffering. By buffering we imply that the input will not be read byte by byte, but rather by chunks of bytes. For example, instead of reading one byte and try to encode it to a character, you read 1024 bytes in an in-memory buffer, and efficiently perform your conversion there. The huge gain of this technique is that it massively reduces the I/O operations needed to read your input, plus the conversion from bytes to characters can be preformed much more efficiently, as it now operates in chucks of bytes and not single bytes.

To make buffering over character streams easy, effective and efficient java offers BufferedReader class. It wraps around a Reader (e.g an InpuStreamReader) and adds that buffering functionality using an internal in-memory buffer. The default size of that buffer is 512 characters, but you can customize it a via BufferedReader(Reader in, int sz) constructor in its int sz argument. Another important functionality that BufferedReader adds, is the ability to read lines of text from a source. It is really very common to want to read a text source line by line, rather than character by character. BufferedReader offers a readLine() method that reads a line from the text source, packs it to a String and returns it to you.

Let’s see some example on how you can use a BufferedReader to read characters from various sources.

1. Obtain a BufferedReader form a file

Let’s see how you can obtain a buffered reader from a file.

BufferedReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class BufferedReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        String str = "";
        char[] chars = new char[100];

        try (BufferedReader bufReader = new BufferedReader(new FileReader(new File(OUTPUT_FILE)),4096)) {

            // read 100 characters from the file
            bufReader.read(chars);
            System.out.println(Arrays.toString(chars));

            // fill the array with blank character for the next invocation
            Arrays.fill(chars,' ');

            // read 20 characters from the file
            bufReader.read(chars,7,20);
            System.out.println(Arrays.toString(chars));

            // read the rest of the file line by line
            while ( (  str = bufReader.readLine() ) != null )
                System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

[o, s, b, c, o, i, a, c, o, i, a, n, i, s, c, n, a, o, n, c, o, a, n, s, c, n, a, o, s, n, c, o, i, a, n, c, i, o, a, n, s, c, i, a, n, c, i, a, n, s, i, c, n, a, s, i, c, n, a, s, i, o, c, n, s, a, o, i, c, n, o, a, i, s, n, c, i, o, a, n, s, c, i, o, n, a, s, o, i, c, n, i, a, s, n, c, i, a, n, s]
[ ,  ,  ,  ,  ,  ,  , o, i, c, n, a, s, c, a, o, s, c, n, a, o, i, s, n, c, i, o,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ]
ancoansicnasoicnaoisncoiasncioancioasncioasc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
...

A first thing to notice is that I’ve specified the internal buffer size of BufferedReader to be 4096 characters. And, as you can see, you can still use the conventional read methods to read character sequence. But the real highlight is readLine(), which enables you to read text files line by line. If you want you can still read bigger chunks at once and then convert them to String on your own. Perhaps, for some reason, you want to read your file 1000 characters at a time, instead of line by line.

BufferedReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        String str = "";
        char[] chars = new char[1000];

        try (BufferedReader bufReader = new BufferedReader(new FileReader(new File(OUTPUT_FILE)),4096)) {

           while( (bufReader.read(chars)) != -1 ) {

               String chunk = new String(chars);
               //alternative
               // String chunk = String.valueOf(chars)

               System.out.println(chunk );
           }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

aosbcoiacoianiscnaoncoanscnaosncoiancioanscianciansicnasicnasiocnsaoicnoaisncioanscionasoicniasnciansoicnascaoscnaoisncioancoansicnasoicnaoisncoiasncioancioasncioasc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
....

Here is a more modern, NIO way … of how you can obtain a BufferedReader form a file:

BufferedReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BufferedReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        String str = "";

        Path filePath = Paths.get(OUTPUT_FILE);

        try (BufferedReader bufReader = Files.newBufferedReader(filePath, Charset.defaultCharset())) {

            // read the rest of the file line by line
            while ( (  str = bufReader.readLine() ) != null )
                System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Obtain a BufferedReader form the standard input

Let’s see how you can obtain a BufferedReader to read text lines from the console.

BufferedReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        String str = "";

        try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.print("Write a line of text :");
            str = bufReader.readLine();
            System.out.println(str );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Write a line of text :Java Code Geeks Rock!
Java Code Geeks Rock!

The above example is quite representative of how you can obtain BufferedReader from a source. From an InputStream, that reads bytes, you get an InpuStreamReader, that reads characters, and buffer it using a BufferedReader.

Download Source Code

This was a Java BufferedReader Example. You can download the source code of this example here : BufferedReaderExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button