Kotlin Read File – 6 Different Ways

Kotlin Read File – We can read the contents of a file in Kotlin either by using standard methods of the 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‘s java.io.File Class, to read the contents of a file.

Example programs to read contents of a file in Kotlin

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

  1. Prepare file object with the location of the file passed as argument to File class constructor.
  2. File.bufferedReader returns a new BufferedReader for reading the content of the file.
  3. Use BufferedReader.readLines() to read the content of the file.

Content of file is printed to the console.

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

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.forEachLine function and read each line of the file.

Content of file is printed to the console.

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

  1. Prepare file object with the location of the file passed as argument to File class constructor.
  2. File.inputStream() returns a new InputStream for the file.
  3. Then you can read bytes from the stream and convert it to a String. This string is content of the file.

Read Content of File to InputStream and then to a String

Content of file is printed to the console.

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

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readBytes() function to get ByteArray. This byte array contains all the file contents.
  3. Use for loop to iterate over the byte array and access the contents of file byte by byte.

Content of file is printed to the console.

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

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readLines() function to get all the lines in the text file as List of Strings.
  3. You can access the list using for loop to read each line of the file.

Content of file is printed to the console.

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

You can also read whole content of the file as a single string. Follow these steps.

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readText() function that returns entire content of file as a String.

Content of file is printed to the console.

Conclusion

In this Kotlin Tutorial – Kotlin Read File, we have learned to read the contents of a file in Kotlin, read a file to a byte array, read a file to InputStream, read a file to list of strings, read a file line by line, read a file to BufferedReader.