Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 134 ยท Text, Files and Time

Paths and Files with NIO

Learn Kotlin's kotlin.io.path API on top of java.nio - Path, the div operator, createTempDirectory, listDirectoryEntries, walk, copyTo, moveTo, attributes and exceptions - with runnable examples.

The previous lesson used java.io.File, which has been in Java since 1996. It works, but it has well-known weaknesses: many methods return false or null on failure without saying why, symbolic links and file attributes are poorly supported, and copying or moving files is awkward. Java 7 introduced a replacement, NIO.2, built on two ideas: java.nio.file.Path represents a location, and java.nio.file.Files holds the operations on it. Failures throw exceptions that tell you what went wrong.

Kotlin wraps this API in the package kotlin.io.path: extension functions that make Path as convenient as File is, plus operators such as / for joining paths. This lesson shows the everyday operations. As in the last lesson, the runner gives your program a temporary working directory that disappears after the run, so we work inside temporary directories and clean up.

Path: building and taking apart

A Path is an immutable value describing a location; like File it does not need to exist. Create one with Path("a", "b") (from kotlin.io.path) and join with the / operator, which reads like a path and picks the right separator for the operating system.

Kotlin Creating and inspecting 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.

Path is Iterable<Path> over its name elements, so map gives the components. normalize() collapses . and .. textually; it does not look at the disk, so it cannot know that a symbolic link made .. mean something else. relativize computes the route from one path to another, which is useful when you want to show paths relative to a project folder.

File and Path convert into each other: file.toPath() and path.toFile(). That lets you call old APIs from new code and the other way around.

Creating and writing

kotlin.io.path mirrors the File helpers: writeText, readText, appendText, readLines, useLines, bufferedWriter and so on exist on Path too. Directories are made with createDirectory and createDirectories (like mkdirs). The big difference: they throw if something is wrong.

Kotlin A temporary directory and some files

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.

createTempDirectory and createTempFile return a fresh, uniquely named location in the temporary directory, which is the safest way to experiment. deleteExisting() throws if the file is gone, deleteIfExists() returns false instead, so pick the one that matches what you expect. fileSize() returns the size in bytes.

Listing a directory

listDirectoryEntries() returns the direct children as a list, optionally filtered by a glob pattern such as "*.txt". forEachDirectoryEntry and useDirectoryEntries are the streaming variants, which should be used for huge directories.

Kotlin listDirectoryEntries with globs

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 glob syntax is not a regex: * matches any characters within one name, ? one character, and {a,b} is an alternative. Because directory order is up to the file system, we sort. Notice that listing returns paths including the directory part; it.name is the file name alone.

Walking a tree

walk() visits every file and directory below a path, lazily, as a Sequence<Path>. It is part of the "path walking" API, which requires the opt-in @OptIn(ExperimentalPathApi::class); the annotation works in ordinary source code. The walk can be tuned: walk(PathWalkOption.INCLUDE_DIRECTORIES) includes directories too, and PathWalkOption.BREADTH_FIRST changes the order.

Kotlin Walking a directory tree

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.

There is also visitFileTree { }, a builder where you register callbacks (onPreVisitDirectory, onVisitFile, ...) and can skip whole subtrees; use it when you need to prune, for example to avoid descending into node_modules or .git. deleteRecursively() removes a directory with everything in it. Treat it like rm -rf: double-check the path before you call it.

Copying and moving

This is where NIO shines. copyTo and moveTo take the target and throw FileAlreadyExistsException unless you pass overwrite = true. moveTo is a rename when source and target are on the same file system. For whole trees there is copyToRecursively.

Kotlin copyTo, moveTo and copyToRecursively

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 exception object carries the offending path in e.file. copyToRecursively needs the followLinks argument to make you decide what happens with symbolic links (copy the link or follow it?). With overwrite = true it replaces existing files at the target.

Exceptions: they tell you what happened

The File API answers failure with false or null. NIO throws specific exceptions, all subclasses of java.io.IOException: NoSuchFileException, FileAlreadyExistsException, DirectoryNotEmptyException, AccessDeniedException, NotDirectoryException. Read them as an inventory of what can go wrong.

Kotlin NIO exceptions in action (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 three failures are caught and named. The last line runs after the directory was deleted, so reading late.txt ends the program with an uncaught java.nio.file.NoSuchFileException. Compare with File.readText() in the last lesson: it also throws, but File.delete() on a non-empty directory just returns false and you never learn why.

Attributes and timestamps

Files can also ask about file metadata: size, whether it is hidden or a symbolic link, permissions, and times of creation and modification. Times and permissions differ per system, and times change on every run, so you should not print them in a test. The example shows how to set a modification time to a known value, which makes it deterministic.

Kotlin File attributes with a fixed timestamp

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.

createTempFile() with no arguments makes a unique file with a generated name. The FileTime class converts to java.time.Instant, which Dates, Times and Durations explains in detail.

File or Path?

For new code, prefer Path:

  • exceptions that explain failures instead of silent false;
  • reliable copy, move and recursive operations, symbolic links, attributes;
  • the / operator and the kotlin.io.path extensions make it just as short as File.

File remains fine for quick scripts and old libraries, and one-liners like File("x").readText() are shorter to type. Convert with toPath()/toFile() at the boundaries. Neither API matters for correctness as much as these habits: build paths with resolve or / (never string concatenation), never trust user-supplied names (a name like ../../etc/passwd escapes your folder: check that base.resolve(name).normalize().startsWith(base) before you use it), and close or delete what you create.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line builds the path data/2026/report.csv in a portable way?

    The div operator from kotlin.io.path joins path elements with the platform's separator. Hard-coded separators are not portable.
  2. 2. What happens when you call copyTo(target) and the target already exists?

    copyTo refuses to overwrite by default. Pass overwrite = true to replace the existing file.
  3. 3. Why should you sort the result of listDirectoryEntries() before printing it?

    Directory order is not specified. Sort when output must be stable.
  4. 4. What does Path.normalize() do?

    normalize works on the text of the path and does not touch the file system. It can therefore be wrong in the presence of symbolic links.
  5. 5. What is the main difference between deleteExisting() and deleteIfExists()?

    Use deleteExisting when the file must be there, and deleteIfExists when absence is fine.

Summary

  • NIO's Path is a location value; kotlin.io.path adds Path(...), the / operator and File-like helpers (readText, writeText, readLines, useLines).
  • createTempDirectory, createTempFile, createDirectories and listDirectoryEntries("*.txt") cover common setup; sort listings for stable output.
  • walk() (opt in with @OptIn(ExperimentalPathApi::class)), copyToRecursively and deleteRecursively handle trees.
  • copyTo and moveTo refuse to overwrite unless told; failures are specific IOException subclasses such as NoSuchFileException.
  • normalize() is textual; guard against path traversal by checking startsWith your base directory after normalizing.
  • Prefer Path for new code, convert with toPath()/toFile() at boundaries.

Next: Dates, Times and Durations