Complete Guide to Reading Text Files and Parsing Numbers into ArrayList in Java

Nov 23, 2025 · Programming · 8 views · 7.8

Keywords: Java File Reading | ArrayList | Exception Handling

Abstract: This article provides a comprehensive analysis of multiple methods for reading numbers from .txt files and storing them in ArrayList in Java. Through detailed examination of best practice code, it explores core concepts including file reading, exception handling, and resource management, while comparing the advantages and disadvantages of different approaches. Written in a rigorous technical paper style, it offers complete code examples and in-depth technical analysis to help developers master efficient file processing techniques.

Fundamentals of File Reading and Core Concepts

Reading numerical data from text files is a common task in Java programming. Based on best practice code, this article provides an in-depth analysis of the complete file reading process. First, it's essential to understand the core components of Java I/O system: the File class represents file paths, BufferedReader provides buffered reading functionality, and ArrayList<Integer> is used for dynamic storage of integer data.

Analysis of Complete Implementation Solution

The following code demonstrates the standard implementation for reading files and parsing numbers:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

System.out.println(list);

In-depth Analysis of Key Components

File Path Handling: The File object encapsulates file system paths, supporting both relative and absolute paths. In practical applications, using the Paths.get() method is recommended for better platform compatibility.

Buffered Reading Mechanism: Wrapping FileReader with BufferedReader significantly improves reading performance. It maintains an internal buffer that reduces the number of underlying system calls. The reading loop uses the readLine() method for line-by-line processing, suitable for number formats separated by newline characters.

Data Type Conversion: The Integer.parseInt() method converts strings to integers. This method throws NumberFormatException, which is not caught in the current implementation—a security vulnerability that needs improvement.

Exception Handling and Resource Management

The code demonstrates a complete exception handling chain: FileNotFoundException handles cases where the file doesn't exist, while IOException addresses various I/O errors during reading. The finally block ensures proper resource release, executing close operations even if exceptions occur.

In modern Java development, using try-with-resources statements is recommended to simplify resource management:

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
    String text;
    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (IOException e) {
    e.printStackTrace();
}

Comparison of Alternative Solutions

Using the Scanner class provides a more concise solution:

Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        integers.add(scanner.nextInt());
    } else {
        scanner.next();
    }
}

Scanner automatically handles whitespace separation, including spaces and newline characters. The combination of hasNextInt() and nextInt() methods provides better type safety and error handling capabilities.

Performance and Scenario Analysis

The BufferedReader solution offers better performance when reading large files due to its buffering mechanism that reduces I/O operations. Meanwhile, Scanner provides richer parsing functionality suitable for handling mixed data types.

For pure number reading scenarios, both methods have their advantages: the former offers finer control granularity, while the latter provides more concise code. Developers should choose the appropriate solution based on specific requirements.

Best Practices Summary

In actual development, it is recommended to: use try-with-resources to ensure resource release; add number format exception handling; consider file encoding issues; and for large-scale data processing, evaluate using NIO's Files.lines() combined with stream processing.

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.