Path: Representing File Locations
Create Path objects, resolve and relativize paths, and manipulate path components.
Introduction to Path
The java.nio.file.Path interface represents a file or directory location in the file system. It replaces the legacy java.io.File class with a richer, platform-independent API.
import java.nio.file.*;
Path p1 = Path.of("/home/user/documents/report.txt");
Path p2 = Paths.get("/home", "user", "documents", "report.txt");
System.out.println(p1); // /home/user/documents/report.txt
System.out.println(p1.equals(p2)); // truePath Components
Extract components of a path:
Path path = Path.of("/home/user/docs/report.txt");
System.out.println(path.getFileName()); // report.txt
System.out.println(path.getParent()); // /home/user/docs
System.out.println(path.getRoot()); // /
System.out.println(path.getNameCount()); // 4
System.out.println(path.getName(0)); // home
System.out.println(path.getName(3)); // report.txtAll lessons in this course
- Path: Representing File Locations
- Files Utility: Read, Write, Copy, Move
- Walking Directory Trees with Files.walk
- WatchService: Monitoring File Changes