Select Page

Reading File in Java using BufferedReader

Joydip Kanjilal
Published: June 18, 2022

Java Developer Tutorials

The BufferedReader class in Java provides a convenient way to read text from a character-input stream. Its read() method can be used to read a specified number of characters or an array of characters. BufferedReader can be used for reading text from a file or stream in Java. It can significantly improve the performance of your program by reading data in larger chunks.

In this Java programming tutorial, we will take a look at how to use the BufferedReader class, its benefits, and how to read data using it.

Want an overview of object-oriented programming (OOP) before proceeding? Check out our Java OOP Tutorial: Classes and Objects in Java.

What is BufferedReader in Java?

BufferReader is a Java class used to read characters, arrays, and lines from an input stream. It is similar to a FileReader but provides buffering functionality as well. You can take advantage of BufferedReader to read data from files, terminals, and other sources.

BufferReader allows fast reading by buffering data, and provides several methods for reading lines of text. This allows you to read large amounts of text more efficiently than if you were reading it directly from the underlying stream.

BufferedReader allows you to read data from files, network sockets, or any other source of characters. It wraps another Reader object and buffers the input, meaning that it stores characters in an internal array so that they can be read back at a later time.

The following Java code example illustrates how you can use the BufferedReader class in Java:

BufferedReader bufferedReader = new BufferedReader(new FileReader("Demo.txt"));

Why Should Developers Use the BufferedReader Class in Java?

BufferedReader reduces the number of I/O operations that would otherwise be needed to read a piece of data by reading the data in chunks and then storing it in an internal buffer. As long as there is data in the buffer, the BufferedReader instance will read data from it rather than the underlying stream.

You can take advantage of the methods of the BufferedReader class to read data from an input stream. For example, the read() method can be used to read a single character, while the readLine() method can be used to read an entire line of text. In addition, BufferedReader provides a skip() method that can be used to skip over a specified number of characters in the input stream.

It should be noted that, without buffering, each call to the read or readLine method would cause bytes to be read from the file and converted to characters before being returned. This is very inefficient, since it is time consuming, as well as resource intensive.

Read: Best Java IDEs and Code Editors

How to Program BufferedReader in Java

To use BufferedReader, programmers first need to import the java.io.BufferedReader package. Then, you can create a BufferedReader object by passing a FileReader object to its constructor. Next, you can call the readLine() method of the BufferedReader class to read a line of text from the file.

There are a few different ways to create a BufferedReader object. The most common way is to pass in an existing Reader object, such as a FileReader or InputStreamReader. You can also mention the size of the buffer in characters, to specify the amount of data that should be read before it needs to be flushed to the underlying stream.

Here is a simple example of how to use BufferedReader to read a file in Java:

public class FileOperations {
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new FileReader("Demo.txt"));
String line = bufferedReader.readLine();
System.out.println(line);
bufferedReader.close();
}
}

The following code example illustrates how you can update the preceding code listing to incorporate exception handling in your Java applications:

public class FileOperations {
public static void main(String[] args) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("Demo.txt"));
String line = bufferedReader.readLine();
System.out.println(line);
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error while retrieving data…");
}
}
}

Programmers can also leverage BufferedReader to create a buffered input stream and then read the data entered as shown in the Java code example below:

import java.io.*;
class BufferedReaderDemo
{
  public static void main(String[] args) throws IOException
  {
    String input;
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);              
    System.out.println("Enter some text:");
    input = bufferedReader.readLine();                                     
    System.out.print("\nThe text entered is: ");
    System.out.println(input);
  }
}

Read: How to Use Optional in Java

What are the Pros and Cons of BufferedReader in Java?

BufferedReader can improve the performance of your Java code by reading larger chunks of data at a time instead of reading one character at a time. It can make your code more efficient by using less CPU cycles. That said, there are also some drawbacks to using BufferedReader in Java.

One potential downside of BufferedReader is that it can lead to OutOfMemoryErrors if the file you are trying to read is very large. This is because the entire contents of the file are loaded into memory all at once. If you are working with particularly large files, it’s best to use another method for reading them.

Alternatives to BufferedReader

If you are looking for an alternative to BufferedReader, there are a few options available. One option is the Scanner class, which is part of the java.util package. Scanner can be used to read from a variety of input sources, including files, strings, and even the console.

Another option is the java.io.InputStreamReader class which allows you to read bytes from an input stream and then convert them into a sequence of characters based on a pre-defined charset. This is generally not as efficient as using a BufferedReader, but is an alternative.

Finally, if you’re working with XML documents, you may want to consider using the javax.xml.parsers.DocumentBuilder class. This class provides a way to parse XML documents and access their contents.

Final Thoughts on Java’s BufferedReader

You can use the BufferedReader class to create a buffer, load data into it (depending on the buffer’s size), and then read data from it. It is an improvement over the InputStreamReader class because it additionally provides buffering to make the reading data much more efficient. Reading from the buffer is much faster and consumes fewer resources.

This Java programming tutorial examined how to use the BufferedReader class to read character input from a stream in Java. We discussed how we could work with BufferedReader in Java, its pros and cons, and alternatives.

Read more Java programming tutorials and software development guides.

Source: www.developer.com