I/O, Serialization & Networking
Files & Paths (NIO.2)
Path models locations, Files performs the operations: read, write, copy, move, walk, watch. This java.nio.file API (Java 7) replaced java.io.File's boolean-returning guesswork with real exceptions and atomic options.Path.of("dir", "file.txt");resolvejoins,relativizeinverts,normalizecleansFiles.readString/readAllLines/linesfor reading;writeString/writefor writingFiles.copy/movewith options:REPLACE_EXISTING,ATOMIC_MOVEFiles.walkstreams a subtree;Files.listone directory — both need try-with-resources- Prefer
Files.createTempFile, check withexists/isRegularFile, delete withdeleteIfExists
Path base = Path.of("/deploy/app");
Path cfg = base.resolve("conf/app.yaml"); // /deploy/app/conf/app.yaml
Path rel = base.relativize(cfg); // conf/app.yaml
Path clean = Path.of("/a/./b/../c").normalize(); // /a/c
Path parent = cfg.getParent();
Path name = cfg.getFileName();Files.createDirectories(target.getParent());
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Files.move(tmp, live, StandardCopyOption.ATOMIC_MOVE); // publish atomically
try (Stream<Path> tree = Files.walk(root)) {
List<Path> bigLogs = tree
.filter(p -> p.toString().endsWith(".log"))
.filter(p -> uncheckedSize(p) > 10_000_000)
.toList();
}The ATOMIC_MOVE idiom — write to a temp file, then atomically rename into place — is how you publish files that other processes read: consumers see either the old file or the complete new one, never a half-written state. (Atomicity holds within a filesystem; cross-device moves fall back to copy+delete.)
WatchService delivers filesystem change events (create/modify/delete per directory); FileSystem abstractions let the same code operate inside zip files (FileSystems.newFileSystem(zipPath)). Legacy interop: path.toFile() and file.toPath() convert freely.