Java Path subpath() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, path.subpath(beginIndex, endIndex) returns the name elements from beginIndex up to, but not including, endIndex, as a new Path. It works like String.substring, except that it counts names instead of characters.

The result is always relative: the root is never part of it, even when beginIndex is 0. For /home/anna/docs/2026/report.txt, subpath(0, 2) is home/anna.

An instance method of the java.nio.file.Path interface, available since Java 7. Call it on a Path object, as in path.subpath(...), after import java.nio.file.Path;.

Syntax

Give the first index to keep and the first index to leave out:

Java
Path p = Paths.get("/home/anna/docs/2026/report.txt");
Path middle = p.subpath(2, 4);                      // docs/2026
Path rest = p.subpath(1, p.getNameCount());          // anna/docs/2026/report.txt
CallWhat it does
p.subpath(0, n)All names without the root (n = getNameCount()).
p.subpath(k, p.getNameCount())Drop the first k folders.
p.subpath(i, i + 1)One element; the same as getName(i).

Since Java 7. The number of elements in the result is endIndex - beginIndex.

Library declarations
Java
// java.nio.file.Path (interface)
Path subpath(int beginIndex, int endIndex)

Parameters

ParameterDescription
beginIndexIndex of the first element to include, from 0 to getNameCount() - 1.
endIndexIndex after the last element to include; greater than beginIndex and at most getNameCount().

Return Value

Return ValueDescription
PathA relative path with endIndex - beginIndex name elements.

Compare with Similar Methods

Other ways to cut a path:

MethodHow it differs
getName(int)Exactly one element.
getParent()Drops only the last element and keeps the root.
relativize(Path)Removes a known prefix path; also works when the paths differ.

Java Examples

Outputs below are shown for Linux and macOS. On Windows, Java prints \ between names instead of /; the note above each output says when a result really differs.

Example 1 — Take Different Ranges of Name Elements

Cut the beginning, the middle, and the end out of one absolute path and check whether the results are absolute.

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

public class PathSubpathBasic {
    public static void main(String[] args) {
        Path p = Paths.get("/home/anna/docs/2026/report.txt");
        int n = p.getNameCount();
        System.out.println("names:          " + n);
        System.out.println("subpath(0, 2) = " + p.subpath(0, 2));
        System.out.println("subpath(2, 4) = " + p.subpath(2, 4));
        System.out.println("subpath(3, n) = " + p.subpath(3, n));
        System.out.println("absolute?       " + p.subpath(0, 2).isAbsolute());
    }
}

How It Works

  1. End is exclusive. subpath(2, 4) keeps indexes 2 and 3 (docs and 2026) and stops before index 4, report.txt.
  2. Up to the end. Passing n, the name count, as the end index keeps everything from index 3 to the last element.
  3. The root is gone. Even the range starting at 0 prints home/anna without a leading slash, and isAbsolute() confirms the result is relative.

Example 2 — Strip the Build Folders from Output Files

A build writes files under build/output. Remove those two leading folders to get the names to publish.

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

public class PathSubpathStrip {
    public static void main(String[] args) {
        Path[] built = {Paths.get("build/output/app/main.js"),
                        Paths.get("build/output/style.css"),
                        Paths.get("build/output/img/icons/home.svg")};
        for (Path b : built) {
            Path published = b.subpath(2, b.getNameCount());
            System.out.println(published + " (" + published.getNameCount() + " names)");
        }
    }
}

How It Works

  1. Skip two names. Starting at index 2 leaves out build and output, whatever comes after them.
  2. The end adapts. b.getNameCount() is evaluated per file, so short and long paths both keep every remaining element.
  3. Fragile when the prefix varies. subpath counts blindly; a file directly in build/ would lose its own name. When the prefix may change, Paths.get("build/output").relativize(b) is safer.

Example 3 — Test Which Ranges subpath() Rejects

Try a valid one-element range, an empty range, an end past the last name, and a negative start.

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

public class PathSubpathErrors {
    static void range(Path p, int begin, int end) {
        String call = "subpath(" + begin + ", " + end + ")";
        try {
            System.out.println(call + " = " + p.subpath(begin, end));
        } catch (IllegalArgumentException e) {
            System.out.println(call + " -> " + e.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        Path p = Paths.get("shop/src/App.java");
        range(p, 1, 2);
        range(p, 2, 2);
        range(p, 1, 4);
        range(p, -1, 2);
    }
}

How It Works

  1. One element is the smallest range. subpath(1, 2) contains only index 1, so it prints src.
  2. Empty ranges are errors. With begin and end both 2 there would be no element at all, and subpath refuses to return an empty path.
  3. Bounds are checked strictly. The path has three names, so an end of 4 and a begin of -1 are both outside the allowed range and throw IllegalArgumentException.

Frequently Asked Questions

A new relative Path with the name elements from beginIndex up to, but not including, endIndex.
No, it is exclusive, like String.substring. subpath(1, 3) returns the elements at indexes 1 and 2.
The root is not a name element, and subpath only copies name elements. The result is therefore always a relative path.
No. endIndex must be greater than beginIndex, so subpath(2, 2) throws IllegalArgumentException.
Call path.subpath(1, path.getNameCount()), after checking that the path has at least two names.

Next: Path.toAbsolutePath()

Turn a relative path into an absolute one based on the working directory.

toAbsolutePath() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful