Lesson · File I/O
NIO.2 (java.nio.file): Path, Files and modern file work
14 min readNIO.2 (java.nio.file)
NIO.2 replaced File with Path and gave the everyday file operations real methods: read and write whole files, stream lines, copy with options, walk trees, and do it all with helpful error messages instead of boolean returns.
Path: an immutable route, built from parts
Path.of("srv", "logs", "app.log") builds a path from segments without string concatenation and without the platform separator question. resolve appends a segment or another path, relativize computes the route from one path to another, normalize removes . and .. segments, and getFileName, getParent and startsWith read the structure.
A Path is still just names: it does not promise a file exists, and existence can change at any moment. The modern improvement is downstream: methods like readString and copy either work or throw IOException with the path and cause, no boolean-and-errno dance.
Path logs = Path.of("srv", "logs"); Path file = logs.resolve("app.log"); // srv\logs\app.log on Windows Path.of("/srv/app", "../etc/passwd").normalize(); // /srv/etc/passwd: .. resolved, not escaped
Files: the one-call operations
Files is the static toolbox over Path: readString and writeString for whole text files (Java 11), readAllLines for line lists, lines() for a lazy Stream<String>, readAllBytes and write for binary, copy, move and deleteIfExists with options like REPLACE_EXISTING and ATOMIC_MOVE, createDirectories for the mkdirs case, and size, isDirectory, getLastModifiedTime for metadata.
Small files get the one-call treatment; large files get the stream treatment. The decision is about memory: readAllBytes materializes the whole file, lines() holds one line at a time but keeps the file open until the stream is closed.
Files.writeString(path, "jvm", StandardCharsets.UTF_8); Files.readString(path); // the whole file long lines = Files.lines(path, StandardCharsets.UTF_8).count(); // lazy, must close Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
Walking trees and listing directories
Files.list(dir) streams the direct children; Files.walk(dir) streams the whole subtree; Files.find adds a predicate for attribute-aware filtering. All three are lazy streams that hold directory handles and must be closed, which try-with-resources handles.
Walk order is not specified, so deterministic output means sorting in the pipeline. And walking a tree you do not own means symlinks and permissions: FOLLOW_LINKS follows links (and can loop), the default does not, and DirectoryIteratorException wraps failures that occur mid-iteration.
try (var paths = Files.walk(root)) { paths.filter(Files::isRegularFile).sorted().forEach(System.out::println); }
Path bench · route arithmetic, not string surgery
pick an operationroot.resolve(Path.of("..", "etc", "passwd")).normalize()
the security pattern: resolve user input against a fixed root, then verify containment before any file operation.
Attributes, permissions and the file system behind
Basic attributes come free: size, isDirectory, getLastModifiedTime, isSymbolicLink. Anything beyond basic (POSIX permissions, owner, DOS flags) goes through FileStore and the views: Files.getFileStore(path).supportsFileAttributeView(...) answers whether the platform can even express what you are asking, before you ask it.
FileSystem and FileStore also explain why some code must be environment-aware: read-only stores, ZIP file systems (FileSystems.newFileSystem for jars as trees), and in-memory test file systems behave differently around delete and atomic move. Check supportsFileAttributeView instead of assuming POSIX.
FileStore store = Files.getFileStore(path); store.supportsFileAttributeView(PosixFileAttributeView.class); // true on Linux, false on Windows NTFS by default
Path traversal: the security rule of file work
The moment a path contains user input, normalization alone is not enough: normalize removes dots but does not stop absolute paths, and an attacker can still escape with .. or a leading /. The safe pattern is build-then-verify: resolve the user segment against a fixed root, then check the final path startsWith the root before any file operation.
The other half of safety is atomicity: writing a file that must be complete or absent uses a temporary file plus move with ATOMIC_MOVE, so readers never observe a half-written state.
Path target = root.resolve(userSegment).normalize(); if (!target.startsWith(root)) throw new SecurityException("path escapes root"); // then read or write target, never the raw input
Any method whose path parameter comes from outside the process is a security boundary. Resolve against a root, verify containment, and only then touch the file system.
Path plus Files is the working pair
Compose routes with Path, execute with Files, close the streams you open, and verify user-supplied paths against a root. File stays for compatibility; the new pair is what new code should read like.
Interview angles
Path versus File?+
Path is an immutable, composable route with structural operations (resolve, relativize, normalize) and first-class errors from the Files API. File is the legacy path class with boolean-returning checks and platform-specific string handling.
readAllBytes versus a stream over lines?+
readAllBytes (and readString) materialize the whole file: fine for small files, fatal for large ones. lines() yields a lazy stream suitable for scanning huge files, but the stream holds an open file handle and must be closed.
How do you copy a file safely?+
Files.copy(from, to, REPLACE_EXISTING) for straightforward copies; for 'complete or absent' semantics write to a temp file and Files.move with ATOMIC_MOVE within the same file store.
Why does normalize() not make a user path safe?+
It removes . and .. textually but does not prevent absolute paths or combinations that escape the intended root. Safety comes from resolving against a fixed root and verifying the result startsWith that root.
What does walk() return and what must you do with it?+
A lazy Stream<Path> over the subtree that keeps directory handles open: use it inside try-with-resources. Order is unspecified, symlinks are not followed unless you pass FOLLOW_LINKS, and mid-iteration failures arrive wrapped in DirectoryIteratorException.