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

Nov 14, 2025 · Programming · 14 views · 7.8

Keywords: Java | File Reading | ArrayList | Text Parsing | Stream API

Abstract: This article provides a comprehensive guide on reading text files containing space-separated integers and converting them into ArrayLists in Java. It covers traditional approaches using Files.readAllLines() with String.split(), modern Java 8 Stream API implementations, error handling strategies, performance considerations, and best practices for file processing in Java applications.

Introduction

File reading is a fundamental operation in Java programming. This article addresses the common requirement of reading space-separated integer values from text files and storing them in ArrayLists. Given example file content like 1 62 4 55 5 6 77, the goal is to convert these values into an integer list: [1, 62, 4, 55, 5, 6, 77].

Basic File Reading Methods

Java offers multiple approaches for file reading, with Files.readAllLines() being a convenient method for text files. This method returns a List<String> containing all lines from the file, suitable for small to medium-sized files.

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

When using this method, ensure correct file paths and proper access permissions. If the file doesn't exist or cannot be read, an IOException will be thrown.

String Splitting and Parsing

After obtaining file content, use the String.split() method to split each line by spaces. The regular expression \s+ matches one or more whitespace characters, including spaces, tabs, etc.

String[] parts = line.split("\s+");

The resulting string array needs conversion to integer types. The Integer.valueOf() method parses strings into Integer objects, throwing NumberFormatException for invalid formats.

Complete Implementation

Combining these methods, the complete traditional implementation is:

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\s+")) {
        Integer i = Integer.valueOf(part);
        numbers.add(i);
    }
}

This implementation assumes no empty lines or leading/trailing whitespace. In practice, add appropriate null checks and exception handling.

Java 8 Stream API Implementation

For developers using Java 8 or later, Stream API offers a more concise functional programming approach:

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\s+"))
    .flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());

This method uses Files.lines() to get a stream of file lines, processes split strings through map() and flatMap() operations, and finally collects results into a list. Stream API advantages include concise code and easy parallelization.

Alternative Approach: Scanner Class

Beyond these methods, Java provides the Scanner class for file reading, particularly useful for parsing file content by specific types (like integers):

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()) {
    integers.add(fileScanner.nextInt());
}

Scanner automatically handles whitespace delimiters and provides rich methods to check next token types. This approach is simple and intuitive, especially suitable for well-formatted numeric files.

Error Handling and Best Practices

Practical applications must consider various exception scenarios:

Use try-with-resources statements to ensure proper resource cleanup:

try (Scanner scanner = new Scanner(new File("file.txt"))) {
    // Process file content
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + e.getMessage());
}

For large files, consider using BufferedReader for line-by-line reading to avoid loading entire files into memory.

Performance Comparison and Selection Guidelines

Different methods excel in various scenarios:

Choose the most appropriate method based on specific requirements, considering file size, performance needs, and code maintainability.

Conclusion

Java offers diverse and flexible file reading solutions, from traditional loop-based processing to modern Stream API approaches. Developers can select the most suitable method based on project requirements and Java versions. Proper error handling and resource management are crucial for program stability. As Java evolves, file processing APIs continue to improve, providing developers with more efficient and secure solutions.

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.