A Comprehensive Guide to Reading and Displaying Data from .txt Files in Java

Nov 23, 2025 · Programming · 8 views · 7.8

Keywords: Java | File Reading | BufferedReader | Scanner | Text Processing

Abstract: This article explores various methods for reading and displaying data from .txt files in Java, focusing on efficient approaches with BufferedReader and comparing Scanner and basic stream operations. Through detailed code examples and performance analysis, it helps developers choose the best file reading strategy.

Introduction

File operations are common tasks in Java programming, especially reading and displaying data from text files. This article starts from basic concepts and gradually introduces several mainstream methods, illustrating their implementation details with code examples.

Reading Files with BufferedReader

BufferedReader is an efficient choice for reading text files in Java, as it reduces I/O operations through buffering. Here is a complete example showing how to read a file and display its content line by line:

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

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

In this example, we first create a BufferedReader object wrapped around a FileReader to read the specified file. Using a while loop, we read each line until the readLine method returns null, indicating the end of the file. Each line is printed to the console via System.out.println. It is crucial to close the stream in the finally block to release system resources.

Reading Files with Scanner Class

In addition to BufferedReader, the java.util.Scanner class offers a flexible way to read files. Scanner is suitable for scenarios requiring text parsing, such as reading words or lines. The following code demonstrates its basic usage:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        try {
            Scanner fileIn = new Scanner(new File("example.txt"));
            while (fileIn.hasNextLine()) {
                String line = fileIn.nextLine();
                System.out.println(line);
            }
            fileIn.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

The hasNextLine method checks if there are more lines to read, and nextLine reads the next line. This approach is straightforward but may be less efficient than BufferedReader, especially for large files.

Basic Stream Operations Explained

For more granular control, a combination of FileInputStream, InputStreamReader, and BufferedReader can be used. This method allows specifying character encoding to correctly read text files with different encodings. Example code is as follows:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class StreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt");
             InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here, we use the try-with-resources statement to automatically manage resources, ensuring streams are closed properly after operations. The InputStreamReader specifies UTF-8 encoding, making it suitable for internationalization scenarios.

Performance and Use Case Analysis

BufferedReader excels in performance for large files due to reduced disk I/O. Scanner is better for interactive or parsing tasks but may consume more memory. Basic stream operations offer maximum flexibility but increase code complexity. In real-world projects, choose the appropriate method based on file size, encoding requirements, and performance needs.

Conclusion

This article provides a detailed overview of various methods for reading and displaying data from .txt files in Java, highlighting the efficiency of BufferedReader and the convenience of Scanner. Through code examples and comparisons, readers can grasp core concepts and apply them in practical development. Always handle exceptions and close resources to ensure code robustness.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.