Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Reading Files in Java with BufferedReader – A Practical Guide with Examples

How to read a file in Java?

Java offers a variety of I/O classes for file operations. The most efficient way to read text files is through java.io.BufferedReader, which wraps a lower‑level Reader and buffers input to reduce expensive system calls.

What is BufferedReader in Java?

BufferedReader is a class that reads text from an input stream (such as a file) by buffering characters. This allows for fast, line‑by‑line or block‑by‑block reading without making a system call for each character.

Because methods like read() on FileReader or InputStreamReader can be costly, wrapping them in a BufferedReader is a common practice to improve performance.

A typical usage pattern looks like this:

BufferedReader reader = new BufferedReader(new FileReader("D:\\DukesDiary.txt"));

Here the file is opened and buffered for efficient reading.

To display the file’s contents, iterate through each line until the end of the file is reached:

String currentLine;
while ((currentLine = reader.readLine()) != null) {
    System.out.println(currentLine);
}

The loop terminates when readLine() returns null, indicating that the end of the file has been reached.

BufferedReader Example (Pre‑JDK 7)

Below is a complete, production‑ready example that demonstrates best practices for resource handling:

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

public class ReadFileExample {

    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("D:\\DukesDiary.txt"));
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                System.out.println(currentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

The finally block guarantees that the reader is closed, freeing system resources even if an exception occurs.

BufferedReader Example (JDK 7+ with Try‑With‑Resources)

With Java 7 and later, the try‑with‑resources statement simplifies cleanup. The following example shows the same logic in a more concise form:

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

public class ReadFileExampleJDK7 {

    private static final String FILENAME = "D:\\DukesDiary.txt";

    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {
            String currentLine;
            while ((currentLine = br.readLine()) != null) {
                System.out.println(currentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using try‑with‑resources automatically closes the BufferedReader, making the code cleaner and less error‑prone.

Java

  1. Mastering Java BufferedReader: Efficient Character Stream Handling
  2. Java Hello World: Step‑by‑Step Guide to Writing Your First Java Program
  3. Encapsulation in Java: A Comprehensive Guide with Practical Example
  4. Java String length() Method: How to Get a String’s Size (Example)
  5. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  6. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  7. Java HashMap: A Comprehensive Guide
  8. Mastering the 'this' Keyword in Java: Purpose, Usage, and Practical Examples
  9. Java Interfaces Explained: How to Define and Implement Them with Practical Examples
  10. Mastering Java's split() Method: A Practical Guide with Code Examples