00:00

Path and Paths in Java: Working with File Locations

Last updated:

Before reading, copying or deleting a file with NIO.2, you need a Path: an object that describes where the file is. Path replaces the old File class for this job and adds powerful methods for combining and comparing locations.

This tutorial explains Path and the older Paths helper class, the parts of a path, the most useful methods and two examples.

1. What Are Path and Paths in Java?

  • java.nio.file.Path is an interface (Java 7) that represents a location in a file system. Path objects are immutable and safe to share between threads. Creating one does not touch the disk.
  • java.nio.file.Paths is a small utility class (Java 7) whose get() methods create paths. Since Java 11, Path.of() does the same, and the Paths documentation recommends Path.of() because Paths may be deprecated in a future release.

2. Anatomy of a Path

Anatomy of a Java PathThe path created by Path.of("projects", "shop", "src", "Main.java") has four name elements: getName(0) is projects, getName(1) is shop, getName(2) is src and getName(3) is Main.java. getParent returns projects/shop/src and getFileName returns Main.java. getNameCount is 4 and getRoot is null because the path is relative. The separator is a slash on Linux and macOS and a backslash on Windows.Path.of("projects", "shop", "src", "Main.java")projectsgetName(0)/shopgetName(1)/srcgetName(2)/Main.javagetName(3)getParent() → projects/shop/srcgetFileName()getNameCount() = 4 · getRoot() = null (relative path) · separator: / on Linux and macOS, \ on Windows

Swipe sideways to see the whole diagram.

3. Creating a Path

CodeResult
Path.of("notes.txt")A relative path, resolved against the current folder.
Path.of("data", "2026", "sales.csv")Joins names with the platform separator (Java 11).
Paths.get("data", "sales.csv")The same result through the older factory.
file.toPath()Converts a java.io.File.

4. Commonly Used Path Methods

MethodDescription
getFileName() / getParent() / getRoot()Last element, everything before it, and the root (or null).
getNameCount() / getName(int)Number of elements and the element at an index.
resolve(String other)Appends other to this path.
resolve(String first, String... more)Appends several elements at once (Java 22).
resolveSibling(String other)Replaces the file name, staying in the same folder.
relativize(Path other)The relative path from this path to other.
normalize()Removes redundant . and .. elements.
toAbsolutePath() / toRealPath()Full path; real path with links resolved (checks the disk).
startsWith() / endsWith()Compare whole path elements, not characters.
toFile()Converts to a java.io.File.

5. Example: Exploring and Combining Paths

A build tool works with project paths. None of these operations touches the disk; they only manipulate path names.

PathOperations.java
import java.nio.file.Path;

public class PathOperations {
    public static void main(String[] args) {
        Path source = Path.of("projects", "shop", "src", "Main.java");      // Java 11
        System.out.println("Path:        " + source);
        System.out.println("File name:   " + source.getFileName());
        System.out.println("Parent:      " + source.getParent());
        System.out.println("Name count:  " + source.getNameCount());
        System.out.println("Absolute?    " + source.isAbsolute());

        Path messy = Path.of("projects", "shop", ".", "docs", "..", "src");
        System.out.println("Normalized:  " + messy.normalize());

        Path base = Path.of("projects", "shop");
        System.out.println("Resolved:    " + base.resolve("test").resolve("CartTest.java"));
        System.out.println("Resolved 22: " + base.resolve("test", "CartTest.java"));          // Java 22
        System.out.println("Relative:    " + base.relativize(source));
    }
}
Output
Path:        projects/shop/src/Main.java
File name:   Main.java
Parent:      projects/shop/src
Name count:  4
Absolute?    false
Normalized:  projects/shop/src
Resolved:    projects/shop/test/CartTest.java
Resolved 22: projects/shop/test/CartTest.java
Relative:    src/Main.java

How the code works

  1. Path.of() joins four names; getFileName(), getParent() and getNameCount() inspect the result.
  2. normalize() removes . and the docs/.. pair, leaving projects/shop/src.
  3. resolve() appends names; the two-argument resolve() (Java 22) does it in one call.
  4. relativize() finds the path from projects/shop to the source file.
  5. The output uses /; on Windows, the same program prints \.

6. Example: Building Backup File Names

A document system creates a backup name next to each file, such as invoice-118-backup.pdf.

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

public class BackupNames {

    static Path backupOf(Path file) {
        String name = file.getFileName().toString();
        int dot = name.lastIndexOf('.');
        String base = (dot > 0) ? name.substring(0, dot) : name;
        String ext = (dot > 0) ? name.substring(dot) : "";
        return file.resolveSibling(base + "-backup" + ext);      // same folder, new name
    }

    public static void main(String[] args) {
        Path invoice = Path.of("billing", "2026", "invoice-118.pdf");
        Path notes = Paths.get("billing", "README");                 // older factory, same result type

        System.out.println(invoice + " -> " + backupOf(invoice));
        System.out.println(notes + " -> " + backupOf(notes));
        System.out.println("Same path either way: " + Paths.get("billing", "README").equals(Path.of("billing", "README")));
        System.out.println("Ends with README: " + notes.endsWith("README"));
    }
}
Output
billing/2026/invoice-118.pdf -> billing/2026/invoice-118-backup.pdf
billing/README -> billing/README-backup
Same path either way: true
Ends with README: true

How the code works

  1. getFileName() isolates the name, which is split at the last dot.
  2. resolveSibling() keeps the folder and replaces only the file name.
  3. Paths.get() and Path.of() produce equal paths.
  4. endsWith("README") compares whole name elements.

7. Common Mistakes and Best Practices

  • Building paths with string concatenation. Use Path.of() or resolve() so separators are correct.
  • Expecting a Path to check the disk. Use Files.exists() and other Files methods.
  • Using endsWith(".txt") to check an extension. It compares path elements; use getFileName().toString().endsWith(".txt").
  • Using Paths.get() in new code. Prefer Path.of().

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 7Path and Paths introduced with NIO.2.
Java 11Path.of() factory methods.
Java 22resolve(first, more...) for appending several elements at once.
Java 25All of the above are standard.

9. Summary

  • Path describes a file-system location; it is immutable and does not touch the disk.
  • Create paths with Path.of(); Paths.get() is the older equivalent.
  • resolve(), resolveSibling(), relativize() and normalize() combine and clean paths.
  • Use the Files class to work with the actual files.

Related Tutorials

10. Official Java Documentation References