Skip to main content

Java BufferedReader Class

Introduction to Java BufferedReader Class

Java BufferedReader class is a part of Java IO package and used for reading text from a character-based input stream. It buffers characters making large scale reading of characters, arrays and lines much more efficient.

Creating BufferedReader in Java

To create a BufferedReader, you need to first create an instance of a FileReader and then pass it to the BufferedReader constructor. Here's how you do it:

FileReader reader = new FileReader("file.txt");
BufferedReader bufferedReader = new BufferedReader(reader);

In the above code, we first create a FileReader object by passing the name of the file we want to read as a string to the FileReader constructor. Then, we create a BufferedReader, passing the FileReader object to its constructor.

Reading from BufferedReader

Once you have created a BufferedReader, you can read text from the file using the read(), readLine(), and read(char[] cbuf, int off, int len) methods.

The read() method

The read() method reads a single character from the BufferedReader and returns it as an integer. Here's how you can use it:

int character = bufferedReader.read();
while(character != -1) {
System.out.print((char) character);
character = bufferedReader.read();
}

In the above code, we read characters one by one from the BufferedReader until it returns -1, which indicates that the end of the stream has been reached. We then print each character.

The readLine() method

The readLine() method reads a line of text. Each call to this method returns the next line of the file, or null if the end of the file has been reached.

String line = bufferedReader.readLine();
while(line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}

In the above code, we read lines one by one from the BufferedReader until it returns null, indicating the end of the file. We then print each line.

Closing the BufferedReader

After you're done reading from the BufferedReader, it's important to close it to free up system resources. You can do this using the close() method:

bufferedReader.close();

Always remember to handle or declare the IOException which might get thrown while reading from a file or closing the BufferedReader.

Conclusion

BufferedReader is a powerful class for reading text from a character input stream. It provides methods to read a single character, an array of characters, or an entire line at once, making it versatile and efficient for many use cases.

As you continue to explore Java, you'll find that understanding how to utilize BufferedReader effectively is an essential skill for handling file inputs in your programs.