Lesson 2
Reading Text Files Line-by-Line in Java
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:

Java
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.nio.file.Paths; 5import java.util.List; 6 7public class Main { 8 public static void main(String[] args) throws IOException { 9 // Create a Path object for the specified file 10 Path filePath = Paths.get("example.txt"); 11 12 // Read all lines from the file into a list 13 List<String> lines = Files.readAllLines(filePath); 14 15 // Iterate through each line and output it 16 for (String line : lines) { 17 System.out.println(line); 18 } 19 } 20}

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:

Plain text
110 220 330 440

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

Java
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.nio.file.Paths; 5import java.util.List; 6 7public class Main { 8 public static void main(String[] args) throws IOException { 9 // Create a Path object for the specified file 10 Path filePath = Paths.get("numbers.txt"); 11 // Read all lines into a list 12 List<String> lines = Files.readAllLines(Paths.get(filePath)); 13 // Initialize the variable to hold the sum of integers from the file 14 int totalSum = 0; 15 16 // Iterate through each line, convert to integer, and add to totalSum 17 for (String line : lines) { 18 try { 19 int number = Integer.parseInt(line); 20 totalSum += number; // Add the integer to totalSum 21 } catch (NumberFormatException e) { 22 System.out.println("Invalid number format in line: " + line); 23 } 24 } 25 // Display the total sum 26 System.out.println("The sum of the numbers is: " + totalSum); 27 } 28}
  • 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:

Plain text
1The 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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.