Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 134 · Text, Files and Time

Files and IO

Learn Kotlin file handling with java.io.File - readText, writeText, appendText, useLines, buffered writers, temp files, directories, exceptions and in-memory readers - with runnable examples.

Variables disappear when a program ends. Files are how a program remembers things: settings, logs, exported reports, downloaded data. Kotlin runs on the JVM, so it uses the Java file classes underneath (java.io.File, readers and writers), and the standard library adds a thin layer of extension functions that turn most file jobs into one-liners: readText(), writeText(), readLines(), useLines { }.

This lesson teaches the File class and those extensions. The newer java.nio API has more features and is covered in Paths and Files with NIO. A note about the examples: our runner gives every program a temporary working directory that is thrown away after the run, so we create temporary files and let them vanish. On your own machine the same code would leave real files behind, so the examples clean up after themselves.

A File is only a path

Creating a File object does not touch the disk. It is just a path with helpful methods. The file may not exist, and you can ask it.

Kotlin File objects are paths

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

name, extension and nameWithoutExtension are pure string work on the path. resolve (or the File(parent, child) constructor) glues path pieces together using the right separator for the operating system, which is / on Linux and \ on Windows. That is why the example normalizes the separator before printing: always use resolve instead of concatenating "dir/" + name.

Writing and reading whole files

For small files, two functions cover almost everything: writeText (create or overwrite) and readText. Both use UTF-8 unless you pass a charset. appendText adds to the end. The helper File.createTempFile makes a unique file in the system temporary directory.

Kotlin writeText, appendText and readText

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The most common beginner surprise is writeText: it replaces the whole content without asking. Use appendText to add. The try/finally makes sure the temporary file is removed even if something fails in between, which is the pattern to remember for anything that must be cleaned up. delete() returns a Boolean (it does not throw), so check it if the deletion matters.

Reading line by line

readLines() returns a List<String>; forEachLine { } and useLines { } process a line at a time. The difference matters for big files: readText() and readLines() load everything into memory, while useLines hands you a lazy Sequence<String> and reads as you go.

Kotlin readLines versus useLines

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The lambda of useLines runs while the file is open, and useLines closes it afterwards (see Resources and use). That has a rule: do not let the sequence escape the lambda. Convert to a list (toList()) or compute a final value (count(), firstOrNull) inside. Returning the raw lines sequence would fail later, because the file is already closed. Here is what happens:

Kotlin A sequence escaping useLines (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The sequence is lazy, so reading starts only at toList(), after useLines has already closed the reader. The program prints the file is closed now and then ends with java.io.IOException: Stream closed, thrown from BufferedReader.readLine inside toList(). The fix is to materialize inside the lambda: file.useLines { it.toList() }.

Buffered writers and printWriter

For many small writes, opening, writing and closing again for each one is slow. Instead, open a writer once. bufferedWriter() and printWriter() give you objects that collect output and write it in blocks. Wrap them in use so they are flushed and closed.

Kotlin Writing many lines efficiently

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If you forget use (or close()), the last buffered block may never reach the disk, and the file stays locked on some systems. Another trap is shown by the second block: printWriter() opens the file for writing again from the start, so it replaced the content of the first block. To keep existing text, open in append mode as the last lines do.

Directories

mkdir() creates one directory, mkdirs() creates the whole chain, listFiles() lists the entries (it returns null if the path is not a directory, hence the nullable type), and walk() visits a tree. deleteRecursively() removes a directory with everything in it, so use it carefully.

Kotlin Creating and listing directories

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Sorting matters because listFiles() and walk() return entries in an order the file system chooses, which differs between machines. Any program whose output depends on that order is fragile. relativeTo turns an absolute path into one relative to a base directory, which is what you want for display. Also notice listFiles().orEmpty(): listFiles() returns null when the directory does not exist, and orEmpty() turns that into an empty array.

Copying, renaming, deleting

copyTo(target, overwrite = false) copies a file and throws FileAlreadyExistsException if the target exists and you did not allow overwriting. renameTo moves or renames and reports success as a Boolean. copyRecursively copies a directory tree.

Kotlin copyTo, renameTo and delete

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note that this exception is Kotlin's own kotlin.io.FileAlreadyExistsException, not the NIO one of the same name, which is why no import was needed.

When files go wrong

Files fail for ordinary reasons: the file is missing, you may not read it, the disk is full. Kotlin has no checked exceptions, so nothing forces you to handle them, and a missing file crashes the program with an exception. Reading a missing file is the textbook example.

Kotlin Reading a missing file (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two reads are handled: FileNotFoundException is a subclass of IOException, and runCatching { ... }.getOrDefault(...) turns a failure into a fallback value. The last read has no handler, so the program stops with an uncaught java.io.FileNotFoundException: definitely-not-here.txt (No such file or directory). For optional files you can also test exists() first, but remember that the file could vanish between the check and the read, so the exception handler is the reliable part.

In-memory streams: IO without files

Code that reads and writes should not care whether the data lives in a file, a network socket or a string. The JDK abstractions Reader, Writer, InputStream and OutputStream give you that. StringReader and StringWriter (or ByteArrayInputStream and ByteArrayOutputStream) are in-memory versions, great for tests and for programs that cannot rely on a file system.

Kotlin The same function on a string and on a file

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both calls to countWords run the identical code; only the source differs. Designing functions to take a Reader or an Appendable instead of a file name makes them testable without any file system, which is a recurring theme in good design. Reader.useLines is the same idea as File.useLines, available on any Reader.

Text encoding

A file holds bytes; text is bytes plus an encoding. Kotlin's readText() and writeText() default to UTF-8, which is what you almost always want. When a file is in another encoding, pass it explicitly with Charsets.

Kotlin Charsets

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The four-letter word needs 5 bytes in UTF-8 but 4 in Latin-1. Decoding with the wrong charset does not throw; it silently substitutes the replacement character, so always know the encoding of your data.

Practical advice

  • Prefer readText/writeText/readLines for small files and useLines for big ones.
  • Use resolve for paths, never string concatenation with slashes.
  • Close what you open (use), and clean up temporary files.
  • Do not depend on the order of listFiles() or walk(); sort.
  • Accept Reader/Appendable parameters when a function does not need to know the source.
  • Expect failure: missing files, permissions and full disks are normal. Handle IOException where you can do something useful, and let it bubble up elsewhere.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does File("a/b.txt") do on its own?

    A File is just a path. You must call functions such as writeText, readText or exists() to touch the disk.
  2. 2. A file already contains text. What does file.writeText("new") do?

    writeText overwrites. Use appendText (or open a writer in append mode) to keep the existing content.
  3. 3. Why should you not return the Sequence given to the lambda of useLines?

    The reader is closed after the lambda. A lazy sequence read afterwards hits a closed stream. Convert it to a list or compute the final value inside the lambda.
  4. 4. Which approach is best for processing a very large log file line by line?

    readText, readLines and readBytes load the whole file into memory. useLines streams one line at a time.
  5. 5. What is the benefit of a function taking a Reader instead of a File?

    The function depends only on the reading abstraction, so it can be tested with a StringReader and reused with any source.

Summary

  • A File is a path; exists(), isDirectory, name, extension and resolve work on it, while reading and writing touch the disk.
  • readText, readLines, readBytes, writeText, appendText handle small files; writeText overwrites. UTF-8 is the default charset.
  • useLines { }, forEachLine and buffered readers stream large files; never let the lazy sequence escape the lambda.
  • Wrap writers in use so data is flushed and closed; clean up temporary files with try/finally, deleteOnExit() or deleteRecursively().
  • listFiles() can return null and has no fixed order; use orEmpty() and sort. walk() visits whole trees.
  • FileNotFoundException and other IOExceptions are unchecked in Kotlin: handle them with try/catch or runCatching where recovery is possible.
  • Accept Reader, Writer or Appendable in your functions to keep them independent of the file system.

Next: Paths and Files with NIO