Java File I/O (NIO.2)
Java File I/O (NIO.2) tests path manipulation, file operations, directory traversal, and attribute handling with java.nio.file.
Core rules
Pathis an immutable sequence of name elements; create it withPaths.get("dir", "file.txt"). On Java 8, usePaths.get;Path.ofis Java 11+. APathdoes not check existence.resolvecombines paths; if the argument is absolute it replaces the base.relativizeproduces a relative path between two paths.normalizeremoves redundant.and..elements without touching the file system.Filesprovides static operations:exists,isDirectory,createDirectory,createDirectories,copy,move,delete,deleteIfExists,readAllLines,write.Files.copyandFiles.movefail if the target exists unlessStandardCopyOption.REPLACE_EXISTINGis supplied;movecan useATOMIC_MOVE.Files.walk,Files.find, andFiles.listreturn lazy streams that must be closed with try-with-resources.Files.walkincludes the starting path;Files.findfilters with aBiPredicate<Path, BasicFileAttributes>.- Symbolic links are followed by default in many operations; use
LinkOption.NOFOLLOW_LINKSto avoid it.
Worked example
Path base = Paths.get("/data");
Path p = base.resolve("logs/app.txt");
System.out.println(base.relativize(p));
resolve yields /data/logs/app.txt; relativize yields logs/app.txt. Neither call creates or checks the file.
Traps
Paths.getdoes not create a file; useFiles.createFileorFiles.write.Files.deletethrowsNoSuchFileExceptionif the target is missing;deleteIfExistsreturns false instead.- Directory streams and walk streams must be closed.
resolvewith an absolute argument ignores the base path.normalizedoes not resolve symbolic links; usetoRealPathfor that.- Copying a directory with
Files.copycopies only the directory entry, not its contents.