Skip to main content

How to read lines from a file in Kotlin

How to read lines from a file in Kotlin.

Here is a step-by-step tutorial on how to read lines from a file in Kotlin.

Step 1: Open the File

To begin, you need to open the file that you want to read. Kotlin provides the File class from the java.io package to handle file operations. You can create a File object by passing the file path or file name to its constructor.

val file = File("path/to/file.txt")

Replace "path/to/file.txt" with the actual path to your file.

Step 2: Create a BufferedReader

Next, you need to create a BufferedReader object to read the contents of the file. The BufferedReader class provides convenient methods for reading text from a character-based input stream.

val reader = BufferedReader(FileReader(file))

Here, we pass the File object to the FileReader constructor, which in turn is passed to the BufferedReader constructor.

Step 3: Read Lines from the File

Now that you have the BufferedReader object, you can start reading lines from the file. Kotlin provides the readLine() method in the BufferedReader class to read a single line of text from the input stream.

var line: String? = reader.readLine()
while (line != null) {
// Process the line
println(line)

// Read the next line
line = reader.readLine()
}

In the above code, we use a while loop to iterate over each line of the file. The readLine() method returns null when there are no more lines to read, so we check if line is not null to continue reading.

Inside the loop, you can process each line as needed. In this example, we simply print each line to the console.

Step 4: Close the File

After you have finished reading lines from the file, it's important to close the file to release any system resources associated with it. Kotlin provides the close() method in the BufferedReader class for this purpose.

reader.close()

Make sure to call the close() method to properly close the file.

Example: Reading Lines from a File

Here is a complete example that demonstrates how to read lines from a file in Kotlin:

import java.io.BufferedReader
import java.io.File
import java.io.FileReader

fun main() {
val file = File("path/to/file.txt")
val reader = BufferedReader(FileReader(file))

var line: String? = reader.readLine()
while (line != null) {
// Process the line
println(line)

// Read the next line
line = reader.readLine()
}

reader.close()
}

Replace "path/to/file.txt" with the actual path to your file. When you run this code, it will read each line from the file and print it to the console.

That's it! You now know how to read lines from a file in Kotlin using the BufferedReader class.