Path

Path represents a path in the file system (either relative or absolute).It is part of the java.nio.file package introduced in Java 7.

  • Used to locate a file or directory in a file system.
  • Can be used to manipulate file paths easily.
  • Path objects are immutable.
  • Implemented by the class sun.nio.fs.UnixPath or WindowsPath depending on OS (not directly visible).

Path is an interface, so it has no constructors.

How to obtain a Path instance?

Most common way:

Path path = Paths.get("folder/subfolder/file.txt");Code language: JavaScript (javascript)

Commonly Used Methods

Simple Program Using Path

Create a Java program that prints various parts of a file path, such as the file name, parent directory, and whether the path is absolute.

import java.nio.file.Path;
import java.nio.file.Paths;

public class SimplePathExample {
    public static void main(String[] args) {
        Path path = Paths.get("documents/reports/annual_report.pdf");

        System.out.println("Path: " + path);
        System.out.println("File name: " + path.getFileName());
        System.out.println("Parent directory: " + path.getParent());
        System.out.println("Root directory: " + path.getRoot());
        System.out.println("Is absolute? " + path.isAbsolute());
        System.out.println("Absolute path: " + path.toAbsolutePath());
        System.out.println("Normalized path: " + path.normalize());

        System.out.println("Number of elements: " + path.getNameCount());
        System.out.println("First element: " + path.getName(0));
    }
}

Problem Statement:

Build a Java program that:

  1. Accepts a directory path as input.
  2. Lists all files and directories inside it (non-recursive).
  3. Prints the relative path from the given directory to each file.
  4. For each path, print the root, file name, and whether it is absolute.
  5. For all files ending with .log, prints their absolute path.
import java.nio.file.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.stream.Stream;

public class DirectoryPathExplorer {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter directory path: ");
        String inputDir = scanner.nextLine();

        Path dirPath = Paths.get(inputDir);

        if (!Files.isDirectory(dirPath)) {
            System.out.println("The path is not a directory.");
            return;
        }

        System.out.println("Listing files and directories in: " + dirPath.toAbsolutePath());

        try (Stream<Path> entries = Files.list(dirPath)) {
            entries.forEach(path -> {
                // Print root, file name, absolute status
                System.out.println("\nPath: " + path);
                System.out.println("  Root: " + path.getRoot());
                System.out.println("  File name: " + path.getFileName());
                System.out.println("  Is absolute? " + path.isAbsolute());

                // Relative path from dirPath
                Path relativePath = dirPath.relativize(path);
                System.out.println("  Relative to base dir: " + relativePath);

                // Print absolute path if file ends with ".log"
                if (path.getFileName().toString().endsWith(".log")) {
                    System.out.println("  Absolute path for log file: " + path.toAbsolutePath());
                }
            });
        } catch (IOException e) {
            System.err.println("Error reading directory: " + e.getMessage());
        }
    }
}

The Path interface in Java NIO (java.nio.file package) represents a platform-independent file or directory path. It serves as the cornerstone for modern file I/O operations by providing an abstraction over file system paths, replacing the older File class with a more flexible and powerful API.

Path enables easy manipulation of file and directory paths, including operations such as resolving sibling or child paths, normalizing paths, and converting between relative and absolute paths. It works seamlessly with the Files class and other NIO components for efficient file system interactions.

Key benefits include:

  • Platform independence for file system paths,
  • Clear, fluent methods for path manipulation,
  • Integration with file system providers supporting local and remote storage,
  • Improved type safety and more expressive APIs compared to legacy classes.

In summary, the Path interface:

  • Is a fundamental building block for modern file I/O in Java,
  • Enhances portability, readability, and flexibility in file handling,
  • Works hand-in-hand with other NIO APIs to create robust file management solutions.
Scroll to Top