This article covers different ways to read the contents of a file in Kotlin.

1. Using BufferedReader.lines() function

In Kotlin, you can use the BufferedReader.lines() function to get a Stream of lines of text read from BufferedReader.

Download Code

2. Using Files.lines() function

Alternatively, you can use the Files.lines() function to read all lines from a file using the specified charset.

Download Code

3. Using Files.readAllLines() function

Another plausible way to read all lines from a file using the specified charset is to use the Files.readAllLines() function.

Download Code

4. Using Files.readAllBytes() function

Another alternative is to use the readAllBytes() function, which returns a byte array having the bytes read from the specified file. To get a string out of file contents, you can pass the byte array to the String constructor.

Download Code

5. Using Files.readString() function

Finally, you can also use the Files.readString() function to read all characters from a file into a string using the specified charset.

Download Code

That’s all about reading a file in Kotlin.