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.

For most small text files, File.readText() is the shortest option. For line-by-line processing, File.forEachLine(), File.useLines(), or a BufferedReader is usually a better choice. For binary files, use File.readBytes() or an InputStream.

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.

Choose the right Kotlin file reading method

The best way to read a file in Kotlin depends on the type and size of the file. Methods such as readText(), readLines(), and readBytes() load the complete file content into memory. Streaming methods such as forEachLine(), useLines(), bufferedReader(), and inputStream() are more suitable when the file is large or when you want to process the file gradually.

Kotlin file methodReturnsUse it whenMemory behavior
File.readText()StringYou need the whole text file as one string.Loads full file.
File.readLines()List<String>You need all lines as a list.Loads full file.
File.forEachLine()Processes each lineYou want to handle lines one by one.Reads line by line.
File.useLines()Sequence<String> inside a blockYou want lazy line processing with automatic closing.Reads lazily inside block.
File.bufferedReader()BufferedReaderYou need reader-level control.Buffered reading.
File.inputStream()InputStreamYou need byte stream processing.Stream based.
File.readBytes()ByteArrayYou need the complete binary content.Loads full 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.

Kotlin Program – example.kt

</>
Copy
import java.io.File
 
/**
 * Created by www.tutorialkart.com
 * Example program to read contents of a file in Kotlin into BufferedReader
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    val bufferedReader = file.bufferedReader()
    val text:List<String> = bufferedReader.readLines()
    for(line in text){
        println(line)
    }
}

Output

Good Day !
Welcome to Kotlin Tutorials in www.tutorialkart.com.
Learn Kotlin easily here.
Happy learning.

Process finished with exit code 0

Content of file is printed to the console.

When you create a reader directly, close it after use. In Kotlin, the common pattern is to wrap the reader in use { }, so the reader is closed automatically even if an exception occurs.

</>
Copy
import java.io.File

fun main() {
    val file = File("input" + File.separator + "contents.txt")

    file.bufferedReader().use { reader ->
        reader.forEachLine { line ->
            println(line)
        }
    }
}

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.

Kotlin Program – example.kt

</>
Copy
import java.io.File
 
/**
 * Created by www.tutorialkart.com
 * Example program to read contents of a file in Kotlin line by line
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    file.forEachLine { println(it) }
}

Output

Good Day !
Welcome to Kotlin Tutorials in www.tutorialkart.com.
Learn Kotlin easily here.
Happy learning Kotlin.

Process finished with exit code 0

Content of file is printed to the console.

forEachLine() is useful when you do not need to store all lines. For example, you can count matching lines, parse each line, or print each line as it is read.

</>
Copy
import java.io.File

fun main() {
    val file = File("input" + File.separator + "contents.txt")
    var lineCount = 0

    file.forEachLine { line ->
        if (line.isNotBlank()) {
            lineCount++
        }
    }

    println("Non-empty lines: $lineCount")
}

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

Kotlin Program – example.kt

</>
Copy
import java.io.File
import java.io.InputStream
 
/**
 * Created by www.tutorialkart.com
 * Example program to read contents of a file in Kotlin to InputStream
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    var ins:InputStream = file.inputStream()
    // read contents of IntputStream to String
    var content = ins.readBytes().toString(Charset.defaultCharset())
    println(content)
}

Content of file is printed to the console.

Use inputStream() when the file is not simply text, or when another API expects an InputStream. Close the stream after reading. The use { } function is a safe way to do this.

</>
Copy
import java.io.File
import java.nio.charset.Charset

fun main() {
    val file = File("input" + File.separator + "contents.txt")

    val content = file.inputStream().use { input ->
        input.readBytes().toString(Charset.defaultCharset())
    }

    println(content)
}

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.

Kotlin Program – example.kt

</>
Copy
import java.io.File
 
/**
 * Created by www.tutorialkart.com
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    var bytes:ByteArray = file.readBytes()
    for(byte in bytes){
        print(byte.toChar())
    }
}

Content of file is printed to the console.

readBytes() is best suited for small files or binary data that you intentionally want as a complete byte array. For very large files, prefer streaming with inputStream() and process chunks instead of loading the whole file at once.

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.

Kotlin Program – example.kt

</>
Copy
import java.io.File
 
/**
 * Created by www.tutorialkart.com
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    var lines:List<String> = file.readLines()
    for(line in lines){
        println(line)
    }
}

Content of file is printed to the console.

readLines() is convenient when the file is small and you need a list for sorting, filtering, indexing, or reuse. Because it stores every line in memory, avoid it for large log files or large data files.

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.

Kotlin Program – example.kt

</>
Copy
import java.io.File
 
/**
 * Created by www.tutorialkart.com
 */
 
fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    var content:String = file.readText()
    println(content)
}

Content of file is printed to the console.

readText() uses a charset to decode bytes into characters. If the file contains plain English text, the default may work in many environments. For portable programs, specify the charset explicitly when you know the file encoding.

</>
Copy
import java.io.File
import java.nio.charset.Charsets

fun main() {
    val file = File("input" + File.separator + "contents.txt")
    val content = file.readText(Charsets.UTF_8)

    println(content)
}

File.useLines() : Process a large text file lazily in Kotlin

File.useLines() reads lines as a sequence inside a block and closes the underlying reader when the block finishes. This is useful when you want sequence operations such as filter, map, count, or sumOf without keeping the whole file in memory.

</>
Copy
import java.io.File

fun main() {
    val file = File("input" + File.separator + "contents.txt")

    val kotlinLineCount = file.useLines { lines ->
        lines.count { line -> line.contains("Kotlin") }
    }

    println(kotlinLineCount)
}

Do not return the Sequence from outside the useLines() block and try to consume it later. The file reader is closed when the block ends, so consume the sequence inside the block.

Read a Kotlin text file with a specific charset

When reading text files, bytes must be decoded using a character set. If the file is saved as UTF-8, pass Charsets.UTF_8. If it is saved using another encoding, use the matching charset.

</>
Copy
import java.io.File
import java.nio.charset.Charset

fun main() {
    val file = File("input" + File.separator + "contents.txt")

    val content = file.readText(Charset.forName("UTF-8"))

    println(content)
}

Specifying the charset is especially useful when the file has non-ASCII characters, data copied from another system, or content generated by another application.

Handle missing file and read errors in Kotlin

File reading can fail when the file path is wrong, the file does not exist, the program does not have permission, or the file is locked by another process. Check the file before reading when you want a clear message for the user.

</>
Copy
import java.io.File
import java.io.IOException

fun main() {
    val file = File("input" + File.separator + "contents.txt")

    try {
        if (!file.exists()) {
            println("File not found: ${file.path}")
            return
        }

        val content = file.readText()
        println(content)
    } catch (e: IOException) {
        println("Could not read file: ${e.message}")
    }
}

Kotlin read file path notes for Windows, macOS, and Linux

The examples use File.separator so the same code can build a path using the separator of the operating system. You can also pass a complete path to File, but relative paths are resolved from the working directory of the program, not necessarily from the directory where the Kotlin source file is stored.

</>
Copy
import java.io.File

fun main() {
    val relativeFile = File("input" + File.separator + "contents.txt")
    val absoluteFile = relativeFile.absoluteFile

    println(absoluteFile.path)
}

If a file is not found, print file.absolutePath or file.absoluteFile.path once during debugging. It shows the exact path Kotlin tried to read.

Kotlin read file mistakes to avoid

  • Reading a huge file with readText(): It loads the whole file into a single string. Use line-by-line reading for large files.
  • Forgetting to close streams and readers: Use use { }, forEachLine(), or useLines() when possible.
  • Using the wrong charset: If special characters appear incorrectly, specify the charset used by the file.
  • Assuming the source folder is the working directory: Relative paths depend on how the program is run.
  • Using text methods for binary files: Use readBytes() or inputStream() for binary data.

Editorial QA checklist for Kotlin read file examples

  • Confirm each Kotlin code block imports java.io.File when it creates a File object.
  • Check that stream and reader examples either close resources or demonstrate use { }.
  • Verify that full-file methods are clearly separated from line-by-line and lazy reading methods.
  • Ensure charset examples use valid Kotlin constants such as Charsets.UTF_8 or Charset.forName("UTF-8").
  • Keep the file path examples consistent with input/contents.txt so readers can test the snippets easily.

FAQs on reading files in Kotlin

What is the simplest way to read a text file in Kotlin?

The simplest way is File("path/to/file.txt").readText(). It returns the whole file content as a String. Use it for small text files.

How do I read a file line by line in Kotlin?

Use File.forEachLine { } when you want to process each line directly. Use File.useLines { } when you want sequence operations such as filter, map, or count.

What is the difference between readText() and readLines() in Kotlin?

readText() returns the complete file as one String. readLines() returns all lines as a List<String>. Both load the file content into memory.

Which Kotlin file reading method is better for large files?

For large text files, prefer forEachLine(), useLines(), or bufferedReader(). These approaches process the file line by line instead of loading the whole file at once.

How do I read a binary file in Kotlin?

Use File.readBytes() for a small binary file when you need all bytes as a ByteArray. For larger binary files, use File.inputStream() and process the stream in parts.

What this Kotlin read file tutorial covered

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.

For small text files, readText() and readLines() are convenient. For large files, use forEachLine(), useLines(), or bufferedReader(). For binary data or APIs that need streams, use readBytes() or inputStream().