Kotlin – Read File to List

Kotlin – Read File to List

Reading a file into a list, means reading the content of the file into a list object where each line of the file becomes an element of the list.

To read a file into a list, you can use readLines() method the File class from the java.io package. Kotlin’s concise syntax makes this process straightforward and elegant.

In this tutorial, we will to through a step by step process of reading a file and storing its contents in a list in Kotlin, with an example.

Steps to Read a File into a List in Kotlin

To read a file into a list in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object pointing to the desired file.
  3. Use the readLines() method to read all lines from the file into a list.

Kotlin Example Program to Read a File into a List

In this example program, we will read a file named 'example.txt' and store its contents in a list.

Kotlin - Read File to List - Input file

Main.kt

import java.io.File

fun main() {
    val filePath = "example.txt" // Replace with the desired file path
    val file = File(filePath)

    val lines = file.readLines()
    println("File content as list: $lines")
}

Output

File content as list: [This is line 1., This is line 2., This is line 3.]

The output will display the contents of the file as a list, with each line of the file being an element in the list.

Summary

In this Kotlin tutorial, we learned how to read the contents of a file into a list. This method is useful for processing text files line by line, especially when working with structured data or configuration files.