This post will discuss how to read a text file into a String in Kotlin.

1. Using Files class

We can use the readAllBytes() function to read all the bytes from a file. It takes the path to the file and returns a byte array containing the bytes read from the file. To get output in the string format, pass the byte array to the String constructor with a charset for decoding.

Download Code

 
To read the contents of a file as a string, we can use the readAllLines() function, which takes the file’s path and optionally accept the charset to be used for decoding. It returns a list of strings, which can be joined together using the joinToString() function to get a single string.

Download Code

 
The Files.readString() function directly reads all characters from a file into a string. It takes a path to the file and optionally accepts the charset to be used. This is demonstrated below:

Download Code

2. Using Scanner

Another solution involves constructing a Scanner to scan the specified file using the specified charset. This is demonstrated below, using the use() function that automatically take care of closing the scanner.

Download Code

3. Using FileReader

Another option is to use a FileReader to read the whole file into a character array. This is demonstrated below using the use() function that automatically takes care of closing all resources.

Download Code

4. Using Input Stream

The idea here is to open an input stream of bytes and repeatedly read bytes of data from it into a byte array using its read() function. Then pass the byte array to the String constructor to get the output in string format.

Download Code

 
The following solution makes use of the BufferedReader. Each invocation of the readLine() function would read bytes from the file and convert them into characters.

Download Code

That’s all about reading a text file into a String in Kotlin.