This post will discuss how to read a file line-by-line in Kotlin.

1. Using BufferedReader class

The standard solution to read a file line-by-line is using the BufferedReader#readLine() function. Each call to the readLine() function reads the next line from the file and returns it as a string. Following is a simple example demonstrating its usage:

Download Code

 
Alternatively, you can use the BufferedReader#lines() function to shorten the code and improve its readability. It returns the stream of lines of text read from the BufferedReader. A typical invocation for this function would look like this:

Download Code

2. Using Files class

Another plausible way is to use the Files.lines() function to get all lines from the file as a stream. Ensure that the stream is closed promptly after completion of the stream’s operations.

Download Code

 
Alternatively, you can directly use the Files.readAllLines() function to get a list of all lines from a file.

Download Code

3. Using Scanner class

The Scanner class can read each line of the file using its nextLine() function. It can be used along with the hasNextLine() function that returns true only if the scanner has more lines left, as shown below:

Download Code

That’s all about reading a file line-by-line in Kotlin.