Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Java File I/O (NIO.2)

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

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

  • Path is an immutable sequence of name elements; create it with Paths.get("dir", "file.txt"). On Java 8, use Paths.get; Path.of is Java 11+. A Path does not check existence.
  • resolve combines paths; if the argument is absolute it replaces the base. relativize produces a relative path between two paths. normalize removes redundant . and .. elements without touching the file system.
  • Files provides static operations: exists, isDirectory, createDirectory, createDirectories, copy, move, delete, deleteIfExists, readAllLines, write.
  • Files.copy and Files.move fail if the target exists unless StandardCopyOption.REPLACE_EXISTING is supplied; move can use ATOMIC_MOVE.
  • Files.walk, Files.find, and Files.list return lazy streams that must be closed with try-with-resources. Files.walk includes the starting path; Files.find filters with a BiPredicate<Path, BasicFileAttributes>.
  • Symbolic links are followed by default in many operations; use LinkOption.NOFOLLOW_LINKS to 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.get does not create a file; use Files.createFile or Files.write.
  • Files.delete throws NoSuchFileException if the target is missing; deleteIfExists returns false instead.
  • Directory streams and walk streams must be closed.
  • resolve with an absolute argument ignores the base path.
  • normalize does not resolve symbolic links; use toRealPath for that.
  • Copying a directory with Files.copy copies only the directory entry, not its contents.