Introduction and Context Setting

Welcome to another lesson, where we'll dive into the essential technique of reading files line-by-line using Kotlin'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 Kotlin.

Reading Files Line-by-Line

To read a file line-by-line in Kotlin, you can use the Files.readAllLines method to read the lines into a list and then iterate over the list using forEach. Let's see this in action:

import java.nio.file.Files
import java.nio.file.Paths

fun main() {
    // Create a Path object for the specified file
    val filePath = Paths.get("example.txt")

    // Read all lines from the file into a list
    val lines = Files.readAllLines(filePath)
    
    // Iterate through each line and output it
    lines.forEach(::println)
}

Here, Files.readAllLines(filePath) reads lines from example.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 Kotlin.

Assume numbers.txt contains:

10
20
30
40

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

import java.nio.file.Files
import java.nio.file.Paths

fun main() {
    // Create a Path object for the specified file
    val filePath = Paths.get("numbers.txt")

    // Read all lines into a list
    val lines = Files.readAllLines(filePath)

    // Initialize the variable to hold the sum of integers from the file
    var totalSum = 0

    // Iterate through each line, convert to integer, and add to totalSum
    lines.forEach { line ->
        try {
            val number = line.toInt()
            totalSum += number // Add the integer to totalSum
        } catch (e: NumberFormatException) {
            println("Invalid number format in line: $line")
        }
    }
    // Display the total sum
    println("The sum of the numbers is: $totalSum")
}
  • Reading Numbers: Each line is parsed to an integer using line.toInt(), 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 Kotlin — 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 in Kotlin. 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