library
advancedNIO.2 Path & Files API
Use the modern file system API (Path, Files) introduced in Java 7 for file operations.
NIO.2 (Java 7) introduced the Path and Files classes as modern replacements for java.io.File. They're more capable, consistent, and interoperable.
Old File = a paper map (limited, no real-time updates). Path + Files = GPS navigation (detailed, accurate, with real-time traffic/error info).
Key Concepts
1
Path represents a file system path. Created via Path.of("dir", "file.txt") or Paths.get(). Supports resolve(), relativize(), normalize(), getParent(), getFileName().
2
Files is a utility class with static methods for all file operations: read, write, copy, move, delete, walk directory trees, check attributes.
3
Key advantages over java.io.File:
- Meaningful exceptions (FileNotFoundException vs boolean return)
- Atomic operations (Files.move with ATOMIC_MOVE)
- Symbolic link handling
- File attributes (permissions, timestamps)
- FileVisitor for recursive directory traversal
- WatchService for file system events
4
Files utility methods:
- Files.readString(path), Files.readAllLines(path)
- Files.writeString(path, content)
- Files.copy(source, target, REPLACE_EXISTING)
- Files.walk(dir) — returns Stream<Path> for recursive traversal
- Files.list(dir) — returns Stream<Path> for immediate children
- Files.createDirectories(path) — creates parent dirs too