0Pricing
Java Academy · Lesson

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)); // true

Path 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.txt

All lessons in this course

  1. Path: Representing File Locations
  2. Files Utility: Read, Write, Copy, Move
  3. Walking Directory Trees with Files.walk
  4. WatchService: Monitoring File Changes
← Back to Java Academy