Java BufferedReader Class

The BufferedReader class in Java is used to read character streams from a source such as a file or network socket. It provides efficient reading of large amounts of data by buffering the input.

To use the BufferedReader class, you first need to create an instance of it, passing in a Reader object as the source of data to read from. For example, to read from a file, you would create a FileReader object and pass it to the BufferedReader constructor:

FileReader fileReader = new FileReader("myfile.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);

Once you have a BufferedReader instance, you can use its methods to read data from the source. Some of the most commonly used methods include:

  • read(): Reads a single character from the input stream and returns it as an integer value.
  • readLine(): Reads a line of text from the input stream and returns it as a String.
  • ready(): Returns true if the input stream is ready to be read, or false otherwise.

Here’s an example of using a BufferedReader to read lines of text from a file:

try (BufferedReader br = new BufferedReader(new FileReader("myfile.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

In this example, the try block creates a BufferedReader object and reads lines of text from the file using the readLine() method. The while loop iterates over each line of text until the end of the file is reached. Finally, any IOException that occurs during the reading process is caught and printed to the console.

Java BufferedReader class declaration:

The BufferedReader class is part of the java.io package in Java and its declaration is as follows:

public class BufferedReader extends Reader {
    // Fields

    // Constructors
    public BufferedReader(Reader in);
    public BufferedReader(Reader in, int sz);

    // Methods
    public void mark(int readAheadLimit) throws IOException;
    public boolean markSupported();
    public int read() throws IOException;
    public int read(char[] cbuf, int off, int len) throws IOException;
    public String readLine() throws IOException;
    public boolean ready() throws IOException;
    public void reset() throws IOException;
    public long skip(long n) throws IOException;
    public void close() throws IOException;
}

The BufferedReader class extends the Reader class, which means that it inherits all the methods and fields of the Reader class. The BufferedReader class adds its own set of methods for reading data from the input source.

The BufferedReader class has two constructors, one that takes a Reader object as input and one that takes a Reader object and an integer value for the buffer size. The buffer size determines how many characters are read at a time from the input source.

The most commonly used methods of the BufferedReader class include read(), readLine(), and ready(). The read() method reads a single character from the input source, while the readLine() method reads a line of text from the input source. The ready() method returns a boolean value indicating whether the input source is ready to be read.

Java BufferedReader class constructors:

The BufferedReader class in Java has two constructors:

  1. BufferedReader(Reader in): This constructor creates a new BufferedReader object with a default buffer size of 8192 characters. It takes a Reader object as input, which is the source from which the data will be read.

Example usage:

FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
  1. BufferedReader(Reader in, int sz): This constructor creates a new BufferedReader object with a specified buffer size. It takes a Reader object as input, which is the source from which the data will be read, and an integer value that represents the buffer size.

Example usage:

FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader, 1024);

In both constructors, the Reader object passed in as input can be any subclass of the Reader class, such as FileReader, InputStreamReader, or StringReader. The buffer size specified in the second constructor is an integer value that determines the size of the buffer used for reading characters from the input source.

The default buffer size of 8192 characters is used if the second constructor is not called. However, it is recommended to use the second constructor if you know the size of the input source, as it can improve the performance of the BufferedReader object by reducing the number of read operations required.

Java BufferedReader class methods:

The BufferedReader class in Java provides several methods for reading character streams from a source. Some of the most commonly used methods are:

  1. int read() throws IOException: This method reads a single character from the input source and returns it as an integer value. If the end of the input stream has been reached, it returns -1.
  2. int read(char[] cbuf, int off, int len) throws IOException: This method reads up to len characters from the input source into a character array cbuf, starting at the specified offset off. It returns the number of characters read, or -1 if the end of the input stream has been reached.
  3. String readLine() throws IOException: This method reads a line of text from the input source and returns it as a String. It returns null if the end of the input stream has been reached.
  4. boolean ready() throws IOException: This method returns true if the input source is ready to be read, or false otherwise.
  5. void mark(int readAheadLimit) throws IOException: This method marks the current position in the input stream. The readAheadLimit parameter specifies the maximum number of characters that can be read before the mark is invalidated.
  6. void reset() throws IOException: This method resets the input stream to the last marked position.
  7. long skip(long n) throws IOException: This method skips over n characters in the input stream and returns the number of characters skipped.
  8. void close() throws IOException: This method closes the input source and releases any resources associated with it.

These methods can be used to read character data efficiently from a variety of sources, such as files, network sockets, or standard input.

Java BufferedReader Example:

Here’s an example that demonstrates how to use the BufferedReader class in Java to read lines of text from a file:

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

public class Example {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("file.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

In this example, a BufferedReader object is created with a FileReader object as input. The FileReader object reads the contents of a file named “file.txt”. The BufferedReader object is used to read lines of text from the file using the readLine() method, which returns null when the end of the file is reached.

Each line of text is printed to the console using the println() method of the System.out object.

The try-catch-finally block ensures that the BufferedReader object is properly closed and any resources associated with it are released, even if an exception is thrown during the execution of the program.

Reading data from console by InputStreamReader and BufferedReader:

In Java, you can read data from the console using the InputStreamReader and BufferedReader classes. Here’s an example that demonstrates how to read a line of text from the console:

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

public class Example {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter a line of text: ");
            String line = reader.readLine();
            System.out.println("You entered: " + line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

In this example, a BufferedReader object is created with an InputStreamReader object as input, which reads data from the console (represented by the System.in stream).

The readLine() method of the BufferedReader object is used to read a line of text from the console. The text “Enter a line of text: ” is displayed on the console using the print() method of the System.out object.

After the user enters a line of text and presses Enter, the readLine() method returns the line of text, which is stored in a String variable named line. The text “You entered: ” followed by the user’s input is displayed on the console using the println() method of the System.out object.

The try-catch-finally block ensures that the BufferedReader object is properly closed and any resources associated with it are released, even if an exception is thrown during the execution of the program.

Another example of reading data from console until user writes stop:

Sure! Here’s an example that demonstrates how to read data from the console until the user enters the word “stop”:

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

public class Example {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            String line;
            while (true) {
                System.out.print("Enter a line of text (or 'stop' to quit): ");
                line = reader.readLine();
                if ("stop".equalsIgnoreCase(line)) {
                    break;
                }
                System.out.println("You entered: " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

In this example, a BufferedReader object is created with an InputStreamReader object as input, which reads data from the console (represented by the System.in stream).

A while loop is used to repeatedly prompt the user to enter a line of text and read it using the readLine() method of the BufferedReader object. The loop continues until the user enters the word “stop”, at which point the break statement is executed, causing the loop to terminate.

The equalsIgnoreCase() method is used to compare the user’s input with the word “stop” in a case-insensitive manner.

If the user enters any other line of text, it is displayed on the console using the println() method of the System.out object.

The try-catch-finally block ensures that the BufferedReader object is properly closed and any resources associated with it are released, even if an exception is thrown during the execution of the program.