How Java navigates the filesystem: files, paths, and I/O
How NIO.2 represents filesystem locations, what Files does with them, and why the old File API is worth avoiding.
Adetayo Akinsanya2026-11-036 min read
- Java
- Core Java
- I/O
- NIO.2
- Files
- Path

Part 23 of the series.Read How Java reads and writes text: bytes, characters, and encoding (Part 22) first if you have not.
In this article (9 sections)
Path config = Path.of("config/settings.json");
System.out.println(Files.exists(config));
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)
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
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);
Files.readAllBytes does the same without decoding:
byte[] raw = Files.readAllBytes(Path.of("image.png"));
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);
}
}
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();
}
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);
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
);
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);
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();
}
}
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
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
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
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
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);
}
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);
}
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);
}
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
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.
Questions or corrections
Found a mistake or have a question about this breakdown? Reach out directly.