NIO.2 (since Java 7, java.nio.file) provides a modern, feature-rich API for file and directory operations — replacing many java.io.File use cases.

Path

Path replaces File with a cleaner, more powerful interface:

  Path path = Path.of("/home/user/docs/report.txt");
// or
Path path2 = Paths.get("/home", "user", "docs", "report.txt");

System.out.println(path.getFileName());  // report.txt
System.out.println(path.getParent());    // /home/user/docs
System.out.println(path.toAbsolutePath());
System.out.println(Files.exists(path));
  

Files Utility Class

Reading and Writing

  Path file = Path.of("data.txt");

// Read all lines
List<String> lines = Files.readAllLines(file);
String content = Files.readString(file); // Java 11+

// Write
Files.writeString(file, "Hello, World!");
Files.write(file, lines);

// Stream large files
try (Stream<String> stream = Files.lines(file)) {
    stream.filter(line -> line.contains("error"))
          .forEach(System.out::println);
}
  

Copy, Move, Delete

  Path source = Path.of("source.txt");
Path target = Path.of("backup/source.txt");

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Files.delete(source);
Files.deleteIfExists(source);
  

Directory Operations

  Path dir = Path.of("logs");

Files.createDirectory(dir);
Files.createDirectories(Path.of("a/b/c")); // create parent dirs

// Walk directory tree
try (Stream<Path> paths = Files.walk(dir)) {
    paths.filter(Files::isRegularFile)
         .forEach(System.out::println);
}

// Find files
try (Stream<Path> results = Files.find(dir, 3,
        (path, attrs) -> path.toString().endsWith(".log"))) {
    results.forEach(System.out::println);
}
  

File Attributes

  BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Size: " + attrs.size());
System.out.println("Created: " + attrs.creationTime());
System.out.println("Is directory: " + attrs.isDirectory());

// POSIX attributes (Linux/macOS)
PosixFileAttributes posix = Files.readAttributes(path, PosixFileAttributes.class);
Set<PosixFilePermission> perms = posix.permissions();
  

WatchService — File System Monitoring

Watch for file create, modify, and delete events:

  WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Path.of("/tmp/watch");
dir.register(watcher,
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_MODIFY,
    StandardWatchEventKinds.ENTRY_DELETE);

while (true) {
    WatchKey key = watcher.take();
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path filename = ev.context();
        System.out.println(event.kind() + ": " + filename);
    }
    key.reset();
}
  
  Path link = Path.of("link-to-file");
Files.createSymbolicLink(link, Path.of("target.txt"));
Path target = Files.readSymbolicLink(link);
  

Best Practices

  • Use Path and Files instead of java.io.File
  • Use try-with-resources for streams returned by Files.lines() and Files.walk()
  • Use StandardCopyOption explicitly to define overwrite behavior
  • Prefer Files.readString() / Files.writeString() (Java 11+) for simple text files
  • Handle IOException appropriately — NIO.2 methods throw checked exceptions