Files and I/O

suggest change

Kotlin on the JVM uses the Java I/O libraries (java.io and java.nio.file) and adds a layer of extension functions on top of them that make common tasks one-liners. There are two families:

This article covers reading and writing text and binary files, processing large files line by line, streams, directories, copying and moving, file metadata, atomic writes and doing I/O from coroutines.

Related articles: Temporary files, ZIP archives, CSV, Configuration files and Reading input from Command Line.

Paths

A Path represents a location in the file system; it doesn't have to exist. Create one with the Path() function and join segments with the / operator:

import kotlin.io.path.*

fun main() {
    val dir = Path("data")
    val file = dir / "reports" / "2026-q3.csv"

    println(file)                         // data/reports/2026-q3.csv (data\reports\... on Windows)
    println(file.name)                    // 2026-q3.csv
    println(file.nameWithoutExtension)    // 2026-q3
    println(file.extension)               // csv
    println(file.parent)                  // data/reports
    println(file.invariantSeparatorsPathString) // data/reports/2026-q3.csv on every OS
    println(file.isAbsolute)              // false
    println(file.absolute())              // /home/me/project/data/reports/2026-q3.csv

    val base = Path("/srv/app")
    val target = Path("/srv/app/static/css/site.css")
    println(target.relativeTo(base))      // static/css/site.css
    println(Path("a/./b/../c").normalize()) // a/c
}

Relative paths are resolved against the current working directory of the process (System.getProperty("user.dir")), not the location of the .jar file.

Converting between the old and new API is a single call: file.toPath() and path.toFile().

Reading and writing a whole file

For files that comfortably fit in memory, read and write them in one call:

import kotlin.io.path.*

fun main() {
    val p = Path("notes.txt")

    p.writeText("first line\nsecond line\n")   // creates or truncates
    p.appendText("third line\n")

    val text: String = p.readText()
    print(text)

    val lines: List<String> = p.readLines()
    println(lines.size)
    println(lines.last())

    p.writeLines(listOf("alpha", "beta", "gamma"))
    println(p.readLines())

    p.deleteIfExists()
}

Output:

first line
second line
third line
3
third line
[alpha, beta, gamma]

All text functions use UTF-8 by default (unlike some Java APIs that historically used the platform charset). Pass a different Charset when you need one:

p.writeText("café", Charsets.ISO_8859_1)   // é is stored as a single byte
val s = p.readText(Charsets.ISO_8859_1)

Binary content works the same way with ByteArray:

val png = Path("logo.png").readBytes()
println("${png.size} bytes, signature ok: ${png.take(4) == listOf<Byte>(-119, 80, 78, 71)}")
Path("logo-copy.png").writeBytes(png)
Path("log.bin").appendBytes(byteArrayOf(1, 2, 3)) // appendBytes/appendText require an existing file

Open options

writeText, writeBytes, outputStream and friends accept OpenOptions that control what happens when the file exists:

import java.nio.file.StandardOpenOption.*
import kotlin.io.path.*

fun main() {
    val p = Path("lock.txt")
    p.writeText("pid=${ProcessHandle.current().pid()}", Charsets.UTF_8, CREATE_NEW)
    // second call fails because the file already exists
    try {
        p.writeText("other", Charsets.UTF_8, CREATE_NEW)
    } catch (e: java.nio.file.FileAlreadyExistsException) {
        println("already exists: ${e.file}")
    }
    p.deleteIfExists()
}

Common options: CREATE (create if missing), CREATE_NEW (fail if it exists), TRUNCATE_EXISTING, APPEND, SYNC/DSYNC (flush to disk on every write). With no options the default is CREATE, TRUNCATE_EXISTING, WRITE.

Large files: line by line

readText() and readLines() load everything into memory. For big log files or data dumps, stream the lines instead. useLines gives you a lazy Sequence<String> and closes the file when the block returns:

import kotlin.io.path.*

fun main() {
    val log = Path("access.log")
    log.writeLines(
        listOf(
            "200 GET /index.html 512",
            "404 GET /missing 0",
            "200 GET /app.js 20480",
            "500 POST /api/order 0",
            "200 GET /style.css 2048",
        )
    )

    val errors = log.useLines { lines ->
        lines.filter { it.startsWith("4") || it.startsWith("5") }.count()
    }
    println("errors: $errors")

    val totalBytes = log.useLines { lines ->
        lines.sumOf { it.substringAfterLast(' ').toLong() }
    }
    println("bytes served: $totalBytes")

    log.forEachLine { line ->
        if (line.contains("POST")) println("write request: $line")
    }

    log.deleteIfExists()
}

Output:

errors: 2
bytes served: 23040
write request: 500 POST /api/order 0

Don't let the sequence escape the useLines block: val lines = p.useLines { it } returns a sequence over a closed file, and iterating it throws IOException: Stream closed. Turn it into a list inside the block (.toList()) if you really need the data afterwards.

Readers, writers and use

When you need more control (writing many small pieces, reading with a custom parser), open a buffered reader or writer. Anything that implements Closeable should be wrapped in use, which closes it even when an exception is thrown (the equivalent of Java's try-with-resources):

import kotlin.io.path.*

data class Item(val name: String, val qty: Int, val price: Double)

fun main() {
    val items = listOf(Item("apple", 3, 0.5), Item("pear", 1, 0.75), Item("plum", 12, 0.2))
    val report = Path("report.txt")

    report.bufferedWriter().use { w ->
        w.write("name   qty  total")
        w.newLine()
        for (item in items) {
            w.write("%-6s %3d %6.2f".format(item.name, item.qty, item.qty * item.price))
            w.newLine()
        }
    }

    // PrintWriter adds println/printf
    Path("summary.txt").toFile().printWriter().use { out ->
        out.println("items: ${items.size}")
        out.printf("total: %.2f%n", items.sumOf { it.qty * it.price })
    }

    report.bufferedReader().use { r ->
        val header = r.readLine()
        println("header: $header")
        var line = r.readLine()
        while (line != null) {
            println("row:    $line")
            line = r.readLine()
        }
    }
    print(Path("summary.txt").readText())

    report.deleteIfExists()
    Path("summary.txt").deleteIfExists()
}

Output:

header: name   qty  total
row:    apple    3   1.50
row:    pear     1   0.75
row:    plum    12   2.40
items: 3
total: 4.65

Note that String.format uses the default locale; on a machine with a German locale 1.50 becomes 1,50. Pass Locale.ROOT ("%.2f".format(Locale.ROOT, x)) when the output is meant for machines.

Several resources can be nested; each use closes its own resource in reverse order:

Path("in.txt").bufferedReader().use { input ->
    Path("out.txt").bufferedWriter().use { output ->
        input.lineSequence()
            .map { it.trim().uppercase() }
            .filter { it.isNotEmpty() }
            .forEach { output.write(it); output.newLine() }
    }
}

Always use the buffered variants (bufferedReader, bufferedWriter, inputStream().buffered()) when reading or writing in small chunks. Unbuffered streams make a system call per read/write, which can be 100x slower.

Byte streams

InputStream and OutputStream move raw bytes. copyTo copies one stream into another with a buffer and returns the number of bytes copied:

import kotlin.io.path.*

fun main() {
    val src = Path("big.bin")
    src.writeBytes(ByteArray(1_000_000) { (it % 256).toByte() })

    val copied = src.inputStream().use { input ->
        Path("big-copy.bin").outputStream().use { output ->
            input.copyTo(output, bufferSize = 64 * 1024)
        }
    }
    println("copied $copied bytes")

    // read in fixed-size chunks, e.g. to compute a checksum
    val crc = java.util.zip.CRC32()
    src.inputStream().buffered().use { input ->
        val buf = ByteArray(8192)
        while (true) {
            val n = input.read(buf)
            if (n < 0) break
            crc.update(buf, 0, n)
        }
    }
    println("crc32: %08x".format(crc.value))

    src.deleteIfExists()
    Path("big-copy.bin").deleteIfExists()
}

The same copyTo works for any stream: an HTTP response body, a GZIPInputStream, System.in. For hashing a file with SHA-256 see Cryptography.

Structured binary data

DataOutputStream and DataInputStream write primitives in big-endian order. This is handy for simple custom formats:

import java.io.DataInputStream
import java.io.DataOutputStream
import kotlin.io.path.*

data class Point(val id: Int, val x: Double, val y: Double, val label: String)

fun save(path: java.nio.file.Path, points: List<Point>) {
    DataOutputStream(path.outputStream().buffered()).use { out ->
        out.writeInt(0x50545331)        // magic "PTS1"
        out.writeInt(points.size)
        for (p in points) {
            out.writeInt(p.id)
            out.writeDouble(p.x)
            out.writeDouble(p.y)
            out.writeUTF(p.label)
        }
    }
}

fun load(path: java.nio.file.Path): List<Point> =
    DataInputStream(path.inputStream().buffered()).use { inp ->
        require(inp.readInt() == 0x50545331) { "not a points file" }
        List(inp.readInt()) {
            Point(inp.readInt(), inp.readDouble(), inp.readDouble(), inp.readUTF())
        }
    }

fun main() {
    val p = Path("points.bin")
    save(p, listOf(Point(1, 0.5, 1.5, "start"), Point(2, 10.0, -3.25, "end")))
    println("${p.fileSize()} bytes")
    load(p).forEach(::println)
    p.deleteIfExists()
}

Output:

60 bytes
Point(id=1, x=0.5, y=1.5, label=start)
Point(id=2, x=10.0, y=-3.25, label=end)

The file is 60 bytes: an 8-byte header, then 4 + 8 + 8 bytes per point plus the label, which writeUTF stores as a 2-byte length followed by the (modified) UTF-8 bytes: 27 bytes for start and 25 for end.

For anything that has to be read by other languages, prefer an established format (JSON, Protocol Buffers, CBOR via kotlinx.serialization).

Random access

To read or write at arbitrary positions without going through the whole file, use a FileChannel:

import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption.*
import kotlin.io.path.*

fun main() {
    val p = Path("records.dat")
    val recordSize = 16
    p.writeBytes(ByteArray(recordSize * 100))   // 100 empty records

    FileChannel.open(p, READ, WRITE).use { ch ->
        // write record #42
        val buf = ByteBuffer.allocate(recordSize).putLong(42L).putLong(System.currentTimeMillis())
        buf.flip()
        ch.write(buf, 42L * recordSize)

        // read it back
        val read = ByteBuffer.allocate(recordSize)
        ch.read(read, 42L * recordSize)
        read.flip()
        println("id=${read.long}, size=${ch.size()}")
    }
    p.deleteIfExists()
}

Output:

id=42, size=1600

java.io.RandomAccessFile offers the same with seek(), readInt() etc. and is a bit simpler for small tools.

File metadata

import java.nio.file.attribute.BasicFileAttributes
import kotlin.io.path.*

fun main() {
    val p = Path("build.gradle.kts")

    println(p.exists())            // true / false
    println(p.notExists())
    println(p.isRegularFile())
    println(p.isDirectory())
    println(p.isReadable())

    if (p.exists()) {
        println(p.isHidden())                 // on Windows throws NoSuchFileException for a missing file
        println(p.fileSize())                 // bytes, Long
        println(p.getLastModifiedTime())      // 2026-10-17T09:12:44.123Z
        val attrs = p.readAttributes<BasicFileAttributes>()
        println("created ${attrs.creationTime()}, symlink: ${attrs.isSymbolicLink}")
    }
}

exists() followed by an operation is a race: the file can disappear between the two calls. Where it matters, just do the operation and handle the exception.

Directories

import kotlin.io.path.*

@OptIn(ExperimentalPathApi::class)
fun main() {
    val root = Path("site")
    (root / "css").createDirectories()          // like mkdir -p, no error if it exists
    (root / "js").createDirectories()
    (root / "index.html").writeText("<h1>hi</h1>")
    (root / "about.html").writeText("<h1>about</h1>")
    (root / "css" / "site.css").writeText("body{}")
    (root / "js" / "app.js").writeText("console.log(1)")

    // direct children only
    println(root.listDirectoryEntries().map { it.name }.sorted())
    println(root.listDirectoryEntries("*.html").map { it.name }.sorted())

    // whole tree: files only by default
    root.walk()
        .map { it.relativeTo(root).invariantSeparatorsPathString }
        .sorted()
        .forEach { println("  $it") }

    // include directories too
    val dirs = root.walk(PathWalkOption.INCLUDE_DIRECTORIES).count { it.isDirectory() }
    println("directories: $dirs")

    val totalSize = root.walk().sumOf { it.fileSize() }
    println("total size: $totalSize bytes")

    root.deleteRecursively()
    println("exists after delete: ${root.exists()}")
}

Output:

[about.html, css, index.html, js]
[about.html, index.html]
  about.html
  css/site.css
  index.html
  js/app.js
directories: 3
total size: 45 bytes
exists after delete: false

Notes:

With java.io.File the equivalents are mkdirs(), listFiles(), walk() / walkTopDown() and deleteRecursively(). Note that File methods report failure by returning false (or null from listFiles()), while Path methods throw an exception that tells you why.

Copying, moving and deleting

import java.nio.file.StandardCopyOption
import kotlin.io.path.*

@OptIn(ExperimentalPathApi::class)
fun main() {
    val src = Path("a.txt").apply { writeText("hello") }

    src.copyTo(Path("b.txt"))                      // fails if b.txt exists
    src.copyTo(Path("b.txt"), overwrite = true)    // replaces it
    Path("b.txt").moveTo(Path("c.txt"), overwrite = true) // rename / move

    println(Path("b.txt").exists())   // false
    println(Path("c.txt").readText()) // hello

    // copy a whole directory tree
    val from = Path("assets").apply { createDirectories() }
    (from / "img").createDirectories()
    (from / "img" / "x.svg").writeText("<svg/>")
    Path("public").createDirectories()             // the target's parent must exist
    from.copyToRecursively(Path("public/assets"), followLinks = false, overwrite = true)
    println(Path("public/assets/img/x.svg").readText())

    src.deleteExisting()               // throws NoSuchFileException if missing
    Path("c.txt").deleteIfExists()     // returns false if missing
    from.deleteRecursively()
    Path("public").deleteRecursively()
}

moveTo within the same file system is a cheap rename. Across file systems (e.g. to another drive) it copies and deletes, unless you pass StandardCopyOption.ATOMIC_MOVE, in which case it fails instead.

Writing files atomically

If the program crashes or the disk fills up in the middle of writeText, readers see a truncated file. For configuration and state files, write to a temporary file in the same directory and rename it over the target. A rename within one directory is atomic: readers see either the old or the new content, never a mix.

import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.io.path.*

fun Path.writeTextAtomically(text: String) {
    val dir = toAbsolutePath().parent
    val tmp = createTempFile(dir, ".$name.", ".tmp")
    try {
        tmp.bufferedWriter().use { it.write(text) }
        tmp.moveTo(this, StandardCopyOption.ATOMIC_MOVE)
    } catch (e: Throwable) {
        tmp.deleteIfExists()
        throw e
    }
}

fun main() {
    val state = Path("state.json")
    state.writeTextAtomically("""{"counter": 1}""")
    state.writeTextAtomically("""{"counter": 2}""")
    println(state.readText())
    state.deleteIfExists()
}

Output:

{"counter": 2}

For durability across power loss, also force the data to disk before the rename: open the temp file with FileChannel.open(tmp, WRITE) and call channel.force(true) after writing.

Errors

kotlin.io.path functions throw subclasses of java.io.IOException with the offending path in the message:

import java.io.IOException
import java.nio.file.AccessDeniedException
import java.nio.file.NoSuchFileException
import kotlin.io.path.*

fun readConfig(name: String): String? =
    try {
        Path(name).readText()
    } catch (e: NoSuchFileException) {
        println("missing: ${e.file}")
        null
    } catch (e: AccessDeniedException) {
        println("no permission: ${e.file}")
        null
    } catch (e: IOException) {
        println("I/O error: $e")
        null
    }

fun main() {
    println(readConfig("does-not-exist.toml"))
}

Output:

missing: does-not-exist.toml
null

Other common ones are FileAlreadyExistsException, DirectoryNotEmptyException (deleting a non-empty directory with deleteExisting) and NotDirectoryException. The old File.readText() throws java.io.FileNotFoundException instead. More on exception handling in Exceptions.

Reading resources from the classpath

Files bundled in src/main/resources end up inside the .jar, so they are not files on disk and can't be opened with Path(...). Read them through the class loader:

fun resourceText(name: String): String =
    object {}.javaClass.getResourceAsStream(name)
        ?.bufferedReader()
        ?.use { it.readText() }
        ?: error("resource not found: $name")

fun main() {
    // src/main/resources/templates/welcome.txt
    println(resourceText("/templates/welcome.txt"))
}

A leading / makes the name absolute within the classpath; without it the name is relative to the package of the class.

Standard input and output

System.in and System.out are streams too, so the same tools apply. A small filter program that numbers the lines it reads:

fun main() {
    generateSequence(::readlnOrNull).forEachIndexed { i, line ->
        println("%4d  %s".format(i + 1, line))
    }
}
$ printf "foo\nbar\n" | java -jar number.jar
   1  foo
   2  bar

readlnOrNull() returns null at end of input, which ends the sequence. Use System.err.println for diagnostics so they don't mix with the program's output. See Reading input from Command Line for more.

I/O in coroutines

File operations block the calling thread. In coroutine code run them on Dispatchers.IO, which has a large thread pool meant for blocking calls, so they don't starve Dispatchers.Default or the main thread:

import kotlinx.coroutines.*
import java.nio.file.Path
import kotlin.io.path.*

suspend fun countLines(p: Path): Int = withContext(Dispatchers.IO) {
    p.useLines { it.count() }
}

fun main() = runBlocking {
    val files = (1..3).map { i ->
        Path("part$i.txt").apply { writeLines(List(i * 1000) { "line $it" }) }
    }

    val counts = files.map { f -> async { f.name to countLines(f) } }.awaitAll()
    counts.forEach { (name, n) -> println("$name: $n") }

    files.forEach { it.deleteIfExists() }
}

Output:

part1.txt: 1000
part2.txt: 2000
part3.txt: 3000

Blocking file reads are not cancellable mid-call; cancellation takes effect at the next suspension point. See Cancellation and timeouts.

Path vs File cheat sheet

Task kotlin.io.path (Path) kotlin.io (File)
create Path("a", "b"), dir / "x" File("a/b"), File(dir, "x")
read all readText(), readLines(), readBytes() same names
write all writeText(), writeLines(), writeBytes() writeText(), writeBytes()
append appendText(), appendLines(), appendBytes() appendText(), appendBytes()
stream lines useLines {}, forEachLine {} useLines {}, forEachLine {}
exists exists() exists()
mkdir -p createDirectories() mkdirs()
list listDirectoryEntries(glob) listFiles()
walk tree walk() walk()
copy copyTo(target, overwrite) copyTo(target, overwrite)
move moveTo(target, overwrite) renameTo(target) (returns Boolean)
delete deleteIfExists(), deleteRecursively() delete(), deleteRecursively()
errors exceptions with a reason often false / null

Prefer Path: it reports errors properly, supports symbolic links, file attributes and non-default file systems (for example a ZIP file opened with FileSystems.newFileSystem), and it is what the rest of java.nio uses.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents