In this tutorial, you shall learn how to read the contents of a file to a string in Kotlin, using File.readText() function, with example programs.

Kotlin – Read file into a string

To read the complete contents of a file into a string in Kotlin, you can use readText() function of java.io.File class.

Steps to read a file into a string

  1. Consider that we are given a file identified by a path.
  2. Create a file object from the given file path, and call readText() function on the file object. The function returns the contents of given file as a string.
</>
Copy
val file = File("path/to/file")
file.readText()

Example

In the following program, we read the contents of the text file info.txt into a string, and print this string to standard output.

Kotlin - Read a file line by line

Main.kt

</>
Copy
import java.io.File

fun main() {
    val file = File("info.txt")
    val text = file.readText()
    println(text)
}

Output

hello world
foo bar
apple banana

Conclusion

In this Kotlin Tutorial, we learned how to read contents a file into a string using java.io.File.readText() function.