Examples to Read File in Kotlin

We can read contents of a file in Kotlin either by using standard methods provided by java.io.File class, or the methods that Kotlin provides as an extension to java.io.File.

We shall look into example programs for the extension methods, provided by Kotlin to java.io.File Class in Java, to read the contents of file.

Example programs to read contents of a file in Kotlin

File.bufferedReader() : How to read contents of a file into BufferedReader

File.bufferedReader returns a new BufferedReader for reading the content of the file.

File.forEachLine() : Read a file line by line in Kotlin

Output:

File.inputStream() : Read contents of file to InputStream

Read Content of File to InputStream and then to a String

File.readBytes() : returns entire content of file as a ByteArray

File.readLines() : returns entire content of file as a List of lines

File.readText() : returns entire content of file as a single string

 

Conclusion :

In this Kotlin Tutorial, We have learnt how to read the content of a file in Kotlin, to a byte array, input stream, list of strings, line by line, buffered reader.
Documentation of these extension methods is available at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/index.html