Java BufferedReader Class and IO Streams

Introduction to Java IO

Almost all Java programs need to interact with the outside world for taking input and supplying output. There could be three sources from where a program can receive input and send output to. These sources are console IO, file IO, and network IO. In console IO end user usually supplies input by keyboard and receives generated output on display screen. In file IO, input is supplied from and output is redirected to a file stored on disk. In network IO, input comes from a networked resource and output is sent to the networked resource over the network.

Java programs perform I/O through streams. A stream could be thought as a pipe which is linked to a physical device at one end and to a Java program at another end by the Java I/O system. There are following I/O streams supported by Java:

  • Byte Streams handle I/O of raw binary data and perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
  • Character Streams handle I/O of character data. The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization - all without extra effort by the programmer.
  • Buffered Streams optimize input and output by reducing the number of calls to the native API. In Unbuffered I/O each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.
    To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
    A program can convert an unbuffered stream into a buffered stream, where the unbuffered stream object is passed to the constructor for a buffered stream class.
    This article specially emphasizes on Buffered Streams. We will shortly discuss buffered streams (BufferedReader class) in detail and their advantages over byte and character streams.
  • Data Streams handle binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface.
  • Object Streams handle binary I/O of objects. Just as data streams support I/O of primitive data types, object streams support I/O of objects. Most, but not all, standard classes support serialization of their objects. Those that do implement the marker interface Serializable.

Programs Using Java.io.BufferedReader

A program can convert an unbuffered stream into a buffered stream by passing the unbuffered stream object to the constructor for a buffered stream class. For example, In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

After this statement executes, br is a character-based stream that is linked to the console through System.in.

Reading Input Characters

To read a character from a BufferedReader we will use int read() throws IOException. Each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of the stream is encountered. If there goes something wrong it can throw an IOException. The following program demonstrates read() by reading characters from the console until the user types a 'q'. Notice that any I/O exceptions that might be generated are simply thrown out of main(). Such an approach is common when reading from the console, but you can handle these types of errors yourself, if you chose.

/* BufferedReaderCharDemo.java */
// BufferedReader to read characters from the console.
import java.io.*;
class BufferedReaderCharDemo
{
  public static void main(String args[]) throws IOException
  {
    char c;
    BufferedReader br = new
    BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter characters, press 'q' to quit.");
    // read characters
    do
    {
      c = (char) br.read();
      System.out.println(c);
    } while(c != 'q');
  }
}
 
OUTPUT
======
D:\JavaPrograms>javac BufferedReaderCharDemo.java
 
D:\JavaPrograms>java BufferedReaderCharDemo
Enter characters, press 'q' to quit.
krishanq
k
r
i
s
h
a
n
q

This output may look a little odd to you because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER; therefore, this does not make read() valuable for interactive console input.

Reading Input Strings

To read a string from the keyboard we use String readLine() throws IOException that is a member of the BufferedReader class. As you can see, it returns a String object. The following program demonstrates BufferedReader and the readLine() method; the program reads and displays lines of text until you enter the word "stop":

/* BufferedReaderStringDemo */
// Reading string from console.
import java.io.*;
class BufferedReaderStringDemo 
{
  public static void main(String args[]) throws IOException
  {
    // create a BufferedReader using System.in
    BufferedReader br = new BufferedReader(new
    InputStreamReader(System.in));
    String str;
    System.out.println("Enter lines of text.");
    System.out.println("Enter 'stop' to quit.");
    do
    {
      str = br.readLine();
      System.out.println(str);
    } while(!str.equals("stop"));
  }
}
 
OUTPUT
======
D:\JavaPrograms>javac BufferedReaderStringDemo.java
 
D:\JavaPrograms>java BufferedReaderStringDemo
Enter lines of text.
Enter 'stop' to quit.
This is a String
This is a String
stop
stop

Last Word

In this tutorial we discussed reading characters and strings using Java.io.BufferedReader class. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.