Read file content as a list of lines in Kotlin
To read file content as a List<String> in Kotlin, use the File.readLines() extension function from java.io.File. It reads the whole text file, splits it into lines, and returns those lines in the same order as they appear in the file.
This approach is useful when the file is small or medium-sized and you need all lines in memory for printing, filtering, parsing, or converting the data into another structure.
| Kotlin file reading option | What it returns | Best use case |
|---|---|---|
File.readLines() | List<String> | Read all lines from a small or medium text file |
File.useLines() | Sequence<String> inside the block | Process a large file line by line without keeping every line in memory |
Path.readLines() | List<String> | Read all lines using Kotlin path APIs |
Kotlin File.readLines() syntax
The basic syntax of readLines() is:
val lines: List<String> = File("file.txt").readLines()
You can also provide a character set when the file is not encoded with the default UTF-8 charset.
val lines: List<String> = File("file.txt").readLines(Charsets.UTF_8)
Import java.io.File before using File("file.txt").
Example 1 – Read lines in text file as List
In this example, we will read a text file, “file.txt”, present at the root of the project. We will use File.readLines() method.
file.txt
Hello World.
Welcome to Kotlin Tutorial by www.tutorialkart.com.
Learning Kotlin is easy.
example.kt
import java.io.File
/**
* Kotlin Example to read contents of file line by line
*/
fun main(args: Array) {
val fileName :String = "file.txt"
var i :Int = 1
// using extension function readLines
File(fileName).readLines().forEach {
print((i++))
println(": "+it)
}
}
Output
1: Hello World.
2: Welcome to Kotlin Tutorial by www.tutorialkart.com.
3: Learning Kotlin is easy.
Store Kotlin file lines in a List<String>
If you want to use the file content later in the program, assign the result of readLines() to a variable. Each item in the list represents one line from the file.
import java.io.File
fun main() {
val lines: List<String> = File("file.txt").readLines()
println("Total lines: ${lines.size}")
println("First line: ${lines.firstOrNull()}")
}
Output
Total lines: 3
First line: Hello World.
Use firstOrNull() instead of first() when the file may be empty. It avoids an exception and returns null when the list has no elements.
Read Kotlin file lines with UTF-8 charset
Text files may contain special characters, symbols, or non-English text. In such cases, specify the charset explicitly so that Kotlin reads the file content correctly.
import java.io.File
fun main() {
val lines = File("file.txt").readLines(Charsets.UTF_8)
for (line in lines) {
println(line)
}
}
For most modern text files, Charsets.UTF_8 is the expected choice.
Read a large file line by line in Kotlin using useLines()
readLines() loads the complete file content into memory. For a very large file, prefer useLines(), which lets you process lines as a sequence inside a block.
import java.io.File
fun main() {
File("file.txt").useLines { lines ->
lines.forEachIndexed { index, line ->
println("${index + 1}: $line")
}
}
}
Use readLines() when you really need a list. Use useLines() when you only need to scan, print, count, filter, or aggregate lines one at a time.
Read file content as lines using Kotlin Path API
Kotlin also provides path-based file APIs. If your code already works with Path, you can use readLines() from kotlin.io.path.
import kotlin.io.path.Path
import kotlin.io.path.readLines
fun main() {
val lines = Path("file.txt").readLines()
lines.forEach { line ->
println(line)
}
}
This is useful in projects where you prefer Path instead of java.io.File.
Handle missing file while reading lines in Kotlin
If the file path is wrong or the file does not exist, reading the file will fail. Check whether the file exists before calling readLines() when the path may come from user input or configuration.
import java.io.File
fun main() {
val file = File("file.txt")
if (file.exists()) {
val lines = file.readLines()
println(lines)
} else {
println("File not found: ${file.path}")
}
}
For production code, you can also use try–catch when you want to handle file permission issues, invalid paths, or unexpected input/output errors.
import java.io.File
import java.io.IOException
fun main() {
try {
val lines = File("file.txt").readLines()
println(lines)
} catch (e: IOException) {
println("Could not read file: ${e.message}")
}
}
Common mistakes with Kotlin readLines()
- Using a wrong relative path:
File("file.txt")is resolved from the working directory, not always from the source file location. - Using readLines() for huge files: it creates a list of all lines, so memory usage increases with file size.
- Ignoring charset: specify
Charsets.UTF_8when the file may contain special characters. - Assuming the file is never empty: use safe functions such as
firstOrNull()when reading the first line. - Not handling missing files: check
exists()or usetry–catchwhen the file path is not guaranteed.
Kotlin readLines() editorial QA checklist
- The tutorial shows that
File.readLines()returnsList<String>. - The examples include the required
import java.io.Fileorkotlin.io.pathimports. - The file path behavior is explained clearly for
File("file.txt"). - The article distinguishes
readLines()for full-list reading fromuseLines()for large-file processing. - The examples mention charset, empty file safety, and missing file handling where relevant.
FAQs on reading file content as a list of lines in Kotlin
How do I read file content as a list of lines in Kotlin?
Use File("file.txt").readLines(). It returns a List<String>, where each list item is one line from the file.
Does Kotlin readLines() include newline characters?
No. readLines() splits the file into lines and returns the line text without the line separator characters.
Should I use readLines() for a large file in Kotlin?
Use readLines() only when it is acceptable to load all lines into memory. For large files, use useLines() to process the file line by line.
How can I read a Kotlin file line by line with line numbers?
You can call readLines() and then use forEachIndexed to access both the index and the line text.
import java.io.File
fun main() {
File("file.txt").readLines().forEachIndexed { index, line ->
println("${index + 1}: $line")
}
}
How do I read a UTF-8 text file as lines in Kotlin?
Pass the charset to readLines(), as in File("file.txt").readLines(Charsets.UTF_8).
Summary: Kotlin readLines() returns file content as List<String>
In this Kotlin Tutorial – Kotlin Read File to Lines, we have learnt to read content of file line by line. In our next tutorial, we shall learn to write data to file.
TutorialKart.com