Introduction and Context Setting

Welcome to another lesson, where we'll delve into the essential technique of reading files line-by-line using Java's Files and Paths classes. In many practical applications, especially those involving large files such as logs or continuous data streams, processing data one line at a time is crucial for efficient data management. By the end of this lesson, you'll learn how to effectively read and process file data line-by-line using Java.

Reading Files Line-by-Line

To read a file line-by-line in Java, you can use the Files.readAllLines method to read the lines into a List<String>, and then iterate over the list using a for-each loop. Let's see this in action:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        // Create a Path object for the specified file
        Path filePath = Paths.get("example.txt");

        // Read all lines from the file into a list
        List<String> lines = Files.readAllLines(filePath);
        
        // Iterate through each line and output it
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Here, Files.readAllLines(filePath) reads lines from data.txt and stores them in a list. Each line is then printed to the console.

Reading Integers from a File and Finding Their Sum

Imagine needing to process a set of numbers stored in a file — reading each integer and calculating their sum. This is a practical task you can easily accomplish using Files.readAllLines and basic string manipulation in Java.

Assume numbers.txt contains:

10
20
30
40

The following code reads integers from this file and calculates their sum:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        // Create a Path object for the specified file
        Path filePath = Paths.get("numbers.txt");
        // Read all lines into a list
        List<String> lines = Files.readAllLines(Paths.get(filePath));
        // Initialize the variable to hold the sum of integers from the file
        int totalSum = 0;

        // Iterate through each line, convert to integer, and add to totalSum
        for (String line : lines) {
            try {
                int number = Integer.parseInt(line);
                totalSum += number; // Add the integer to totalSum
            } catch (NumberFormatException e) {
                System.out.println("Invalid number format in line: " + line);
            }
        }
        // Display the total sum
        System.out.println("The sum of the numbers is: " + totalSum);
    }
}
  • Reading Numbers: Each line is parsed to an integer using Integer.parseInt(), which safely converts strings to integers.
  • Calculating Sum: The integers are added together in the totalSum variable.

After running this code, it will display the total sum of the numbers:

The sum of the numbers is: 100
Summary and Practice Preparation

In this lesson, you've developed the skills to read a text file line-by-line using Java — a crucial technique for processing large datasets efficiently. You've learned to manage file I/O operations with Files and Paths, and effectively handle each line of text data. You're now well-prepared to tackle practice exercises applying these concepts and further explore parsing techniques in upcoming lessons. Continue building on these skills and enjoy the journey!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal