DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

How Java navigates the filesystem: files, paths, and I/O

How Java navigates the filesystem: files, paths, and I/O

Path config = Path.of("config/settings.json");
System.out.println(Files.exists(config));

Enter fullscreen mode Exit fullscreen mode

config is a path — a description of a location in the filesystem hierarchy. Creating it doesn't open a file, acquire a lock, or verify that anything is on disk. Files.exists is the first contact with the actual filesystem. This distinction is what makes the NIO.2 API in java.nio.file easier to reason about than the older java.io.File.

What a Path represents

A Path is a sequence of name elements separated by the platform's path separator. On Unix it's /; on Windows it's \. Path.of("config/settings.json") has two elements: config and settings.json. Path.of("/etc/hosts") has two elements under the root /.

Path.of() was added in Java 11. Before that, the equivalent was Paths.get() (available since Java 7). They return the same thing; Path.of just moved the factory into the interface itself.

A path can be absolute or relative. Path.of("/etc/hosts") is absolute: it starts from the filesystem root. Path.of("config/settings.json") is relative: it means "relative to whatever the current working directory turns out to be."

A few operations that work on the path string alone, without touching the disk:

Path p = Path.of("/var/log/app/errors.log");

p.getFileName(); // errors.log
p.getParent(); // /var/log/app
p.getRoot(); // /

p.getName(0); // var (first element after root)
p.getNameCount(); // 4 (var, log, app, errors.log)

Enter fullscreen mode Exit fullscreen mode

resolve() appends a path to another:

Path base = Path.of("/var/log");
Path full = base.resolve("app/errors.log");
// full is /var/log/app/errors.log

Enter fullscreen mode Exit fullscreen mode

If the argument to resolve is absolute, it replaces the base entirely: base.resolve("/etc/hosts") returns /etc/hosts. That's by design — it makes it safe to pass either a relative or absolute path without special-casing.

normalize() removes . and .. components. Path.of("/var/log/../log/app/./errors.log").normalize() returns /var/log/app/errors.log.

Reading files

Files.readString (Java 11+) reads an entire file into a String:

String content = Files.readString(Path.of("message.txt"), StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

Files.readAllBytes does the same without decoding:

byte[] raw = Files.readAllBytes(Path.of("image.png"));

Enter fullscreen mode Exit fullscreen mode

Both load the whole file at once. For small files — configs, templates, test data — that's fine. For large files, read line by line instead:

try (BufferedReader reader = Files.newBufferedReader(
        Path.of("large.csv"), StandardCharsets.UTF_8)) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}

Enter fullscreen mode Exit fullscreen mode

Files.lines (Java 8+) wraps the same reader in a Stream<String>, which lets you use stream operations on the lines:

try (Stream<String> lines = Files.lines(Path.of("large.csv"), StandardCharsets.UTF_8)) {
    long count = lines.filter(l -> l.startsWith("ERROR")).count();
}

Enter fullscreen mode Exit fullscreen mode

The try-with-resources is not optional here. Files.lines returns a stream backed by an open reader; closing the stream closes the reader. If you forget the try block, you leak a file descriptor.

Writing files

Files.writeString (Java 11+) writes a String to a file, creating it if it doesn't exist:

Files.writeString(Path.of("output.txt"), content, StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

By default it truncates the file. To append instead:

Files.writeString(
    Path.of("log.txt"),
    "new entry\n",
    StandardCharsets.UTF_8,
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND
);

Enter fullscreen mode Exit fullscreen mode

CREATE creates the file if absent; without it, the write fails on a missing file. APPEND positions the write at the end of the existing content.

For raw bytes, Files.write:

Files.write(Path.of("data.bin"), bytes);

Enter fullscreen mode Exit fullscreen mode

It accepts the same StandardOpenOption varargs.

For large text output, Files.newBufferedWriter avoids holding the entire string in memory:

try (BufferedWriter writer = Files.newBufferedWriter(
        Path.of("report.txt"), StandardCharsets.UTF_8)) {
    for (String line : lines) {
        writer.write(line);
        writer.newLine();
    }
}

Enter fullscreen mode Exit fullscreen mode

Metadata

Files has a set of methods that read file attributes without opening the file for content:

Path p = Path.of("data.csv");

Files.exists(p); // true if the path names an existing file or directory
Files.isRegularFile(p); // true if it's a regular file (not a directory, symlink, etc.)
Files.isDirectory(p); // true if it's a directory
Files.size(p); // length in bytes; throws if the file doesn't exist
Files.getLastModifiedTime(p); // returns a FileTime

Enter fullscreen mode Exit fullscreen mode

What about symbolic links? Files.exists follows symlinks by default: it returns true if the target exists. Pass LinkOption.NOFOLLOW_LINKS to check whether the symlink itself exists regardless of its target.

Creating and deleting

Files.createDirectory(Path.of("output"));
// throws FileAlreadyExistsException if it exists
// throws NoSuchFileException if the parent doesn't exist

Files.createDirectories(Path.of("output/reports/2026"));
// creates all missing components; does not throw if the path already exists

Enter fullscreen mode Exit fullscreen mode

Files.delete throws NoSuchFileException if the target doesn't exist. Files.deleteIfExists does the same but returns false instead of throwing when nothing was there:

Files.delete(Path.of("temp.bin")); // throws if absent
Files.deleteIfExists(Path.of("temp.bin")); // returns false if absent

Enter fullscreen mode Exit fullscreen mode

You can't delete a non-empty directory with either method. Use Files.walk to traverse and delete contents first (see below), or a recursive helper.

Copying and moving

Files.copy(source, target);
// throws FileAlreadyExistsException if target exists

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// overwrites target if it exists

Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
// on the same filesystem, move is typically atomic

Enter fullscreen mode Exit fullscreen mode

Files.copy can also copy from an InputStream into a file, or from a file into an OutputStream. That's useful when the source isn't a local file:

try (InputStream in = url.openStream()) {
    Files.copy(in, Path.of("downloaded.zip"), StandardCopyOption.REPLACE_EXISTING);
}

Enter fullscreen mode Exit fullscreen mode

Listing and walking directories

Files.list returns a Stream<Path> of the direct children of a directory — one level only, like ls:

try (Stream<Path> entries = Files.list(Path.of("/var/log"))) {
    entries.filter(Files::isRegularFile).forEach(System.out::println);
}

Enter fullscreen mode Exit fullscreen mode

Files.walk descends into subdirectories:

try (Stream<Path> all = Files.walk(Path.of("/var/log"))) {
    all.filter(p -> p.toString().endsWith(".log"))
       .forEach(System.out::println);
}

Enter fullscreen mode Exit fullscreen mode

Both return lazy streams backed by directory iterators; close them to release the underlying resources. The stream from Files.walk visits the starting directory itself first, then its children in depth-first order.

An optional depth argument limits how far walk descends: Files.walk(start, 2) visits the start, its children, and their children, then stops.

Why not java.io.File

Java has had a java.io.File class since version 1.0. You'll encounter it in older code. Its problems:

File.delete() returns a boolean. If deletion fails, you don't know why — no exception, no message. Files.delete(Path) throws an exception with a reason.

File.list() returns null on error (I/O failure, path not a directory). Every call site must null-check. Files.list(Path) throws IOException.

File has no charset support. Reading a file through new FileReader(file) uses the platform default. Files takes charsets explicitly.

Convert a File to a Path with file.toPath(). Convert back with path.toFile(). The two types coexist; NIO.2 didn't remove the old API.

Exercise

Write a method that lists all files under a given directory with a .java extension, returning them sorted by file size (smallest first):

List<Path> javaFilesBySize(Path root) throws IOException

Enter fullscreen mode Exit fullscreen mode

What do you use? Files.walk, filter, sorted with a comparator on Files.size, and toList(). What happens if one of the files is deleted between the walk and the size read?

Files.size throws NoSuchFileException if the file no longer exists. A concurrent delete between listing and sizing is an IOException inside a stream operation. The safe approach is to catch it inside the comparator, treat the missing file as size zero or skip it, or use Files.readAttributes to read size and existence atomically from one BasicFileAttributes read per path.

Top comments (0)