Memra

NIO.2: Path & Files

The modern, preferred file API — clean, readable, and exception-safe.

java.nio.file — the modern API

The java.nio.file package (NIO.2, added in Java 7) replaced java.io.File for most purposes. Two classes do almost everything:

Path represents a file path (not the file itself — just a name/location):

Path home  = Path.of("/home/user");
Path file  = Path.of("/home/user", "notes", "todo.txt");  // varargs segments
Path rel   = Path.of("src/main/java");                    // relative
Path child = home.resolve("docs/readme.txt");             // join paths

Files is a static utility class with methods that actually operate on the file system:

// Existence and metadata
boolean exists = Files.exists(file);
byte[]  raw    = Files.readAllBytes(file);
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
String text        = Files.readString(file);           // Java 11+

// Writing
Files.writeString(file, "content", StandardCharsets.UTF_8);  // Java 11+
Files.write(file, lines);   // write a List<String>

// File system operations
Files.createDirectories(Path.of("a/b/c"));
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
Files.delete(file);          // throws NoSuchFileException if absent
Files.deleteIfExists(file);  // safe version — no exception if absent

All Files methods throw checked IOException (or subclasses like NoSuchFileException), so they must be declared or caught.

NORMAL ~/memra/learn/java-from-zero/nio2-path-files utf-8 LF