How to read a file in Kotlin

March 17, 2021 1 Comment Kotlin File Read

1. Introduction

In this tutorial, we are going to present several ways to read a file in Kotlin. Kotlin is a cross-platform, general-purpose programming language that is becoming more and more popular since it is now the preferred language for Android app development.

Related Posts:

2. Create a file

First, let's create a file for testing purposes with a name frontbackend.txt and the following content:

Tutorials:
    - one
    - two
    - three

We can do it using the touch command on Linux or with a Notepad on Windows. For a sake of simplicity let's put it into a folder with our sample Kotlin files.

3. Read a file using InputStream

3.1. Read all lines at once

The first approach use BufferedReader and use method:

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
    val inputStream: InputStream = File("frontbackend.txt").inputStream()

    val content = inputStream.bufferedReader().use { it.readText() }

    println(content)
}

Here:

  • first, we get an InputStream from File object,
  • next, using inputStream.bufferedReader() we get a BufferedReader responsible for reading streams,
  • finally, to read the content we use the use{ it.readTest() }command which is the same as Closeable.use(Reader.readText()) in Java,
  • note that the last operation will automatically close the InputStream.

The output will be:

Tutorials:
    - one
    - two
    - three

3.2. Read line by line

In the following example we make use of Reader.useLines(...) method to read a file line by line:

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
    val inputStream: InputStream = File("frontbackend.txt").inputStream()
    val out = mutableListOf<String>()

    inputStream.bufferedReader().useLines { lines -> lines.forEach { out.add(it) } }

    out.forEach { println(it) }
}

In this example:

  • first, we read an InputStream of a frontbackend.txt file,
  • next, we created a mutable list that will hold file content lines,
  • then, we read all lines and put them in our collection using the bufferedReader().useLines method,
  • the final step is to print all lines from our collection.

If everything is correct you should get the same result as in the first approach:

Tutorials:
    - one
    - two
    - three

4. Conclusion

In this short article, we presented ways to read a file in Kotlin. The first method read all file content at once, second read line by line.

{{ message }}

{{ 'Comments are closed.' | trans }}