Java Path startsWith() Method

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

Definition

In Java, path.startsWith(other) returns true when path begins with the same root and the same whole name elements as other. /home/anna/docs starts with /home/anna and with /, but not with /home/an, because an is not a complete name.

It compares names, not characters, and it does not touch the disk. An absolute path never starts with a relative one, so /home/anna does not start with home.

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

Syntax

Pass another Path or a String that is converted to a path first:

Java
Path file = Paths.get("/home/anna/docs/report.txt");
boolean a = file.startsWith("/home/anna");               // true
boolean b = file.startsWith(Paths.get("/home/an"));      // false: not a whole name
CallWhat it does
p.startsWith(Path other)Same root and the first names of p equal all names of other.
p.startsWith(String other)Shortcut for p.startsWith(p.getFileSystem().getPath(other)).
p.normalize().startsWith(base)Inside-the-folder check after removing ...

Since Java 7. The String overload became a default method in Java 11; the behaviour is unchanged.

Library declarations
Java
// java.nio.file.Path (interface)
boolean startsWith(Path other)
boolean startsWith(String other)

Parameters

ParameterDescription
otherThe prefix to test, as a Path or as a String that is parsed like Paths.get. Must not be null.

Return Value

Return ValueDescription
trueThe path begins with other, element by element (equal paths also count).
falseOtherwise, including a root mismatch or a path from another file system provider.

Compare with Similar Methods

Similar checks:

MethodHow it differs
endsWith()Compares the last name elements instead of the first.
String.startsWithCompares characters, so "/home/anna" "starts with" "/home/an".
relativize()After a successful check, gives the part below the prefix.

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 — Compare Path.startsWith with String.startsWith

Test one absolute path against a whole folder, a partial name, a relative prefix, and the root, then repeat the partial test on the text.

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

public class PathStartsWithBasic {
    public static void main(String[] args) {
        Path p = Paths.get("/home/anna/docs/report.txt");
        System.out.println("startsWith(\"/home/anna\"): " + p.startsWith("/home/anna"));
        System.out.println("startsWith(\"/home/an\"):   " + p.startsWith("/home/an"));
        System.out.println("startsWith(\"home/anna\"):  " + p.startsWith("home/anna"));
        System.out.println("startsWith(\"/\"):          " + p.startsWith("/"));
        System.out.println("text startsWith /home/an: " + p.toString().startsWith("/home/an"));
    }
}

How It Works

  1. Whole names only. /home/anna matches the first two elements exactly; /home/an fails because an is compared with anna as a complete name.
  2. Roots must match too. home/anna has the right names but no root, so it is not a prefix of an absolute path; the bare root / is a prefix of every absolute path.
  3. Strings compare characters. The last line uses String.startsWith, which happily matches half a folder name: the reason to prefer the Path method for folder checks.

Example 2 — Keep User File Names Inside an Upload Folder

Join untrusted names onto a base folder, clean them with normalize(), and accept only results that still start with the base. This blocks path traversal tricks such as ../../etc/passwd.

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

public class PathStartsWithTraversal {
    public static void main(String[] args) {
        Path base = Paths.get("/srv/uploads");
        String[] requests = {"cat.png", "albums/2026/dog.png", "../../etc/passwd",
                             "albums/../../secret.txt", "/etc/passwd"};
        for (String r : requests) {
            Path target = base.resolve(r).normalize();
            if (target.startsWith(base)) {
                System.out.println("OK       " + r + " -> " + base.relativize(target));
            } else {
                System.out.println("REJECTED " + r);
            }
        }
    }
}

How It Works

  1. Join, then clean. resolve glues each request onto /srv/uploads and normalize cancels every .., so ../../etc/passwd turns into /etc/passwd before it is checked.
  2. Hidden escapes are caught. albums/../../secret.txt looks harmless, but after cleaning it becomes /srv/secret.txt, which no longer starts with the base, so it is rejected.
  3. Absolute input replaces the base. resolve returns an absolute argument unchanged, so /etc/passwd is also rejected; accepted names are printed relative to the base. Symbolic links inside the folder need an extra toRealPath() check.

Example 3 — Pick Only the Files Inside src/test

A text check would also match src/testdata. Compare it with the Path check while filtering a list of project files.

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

public class PathStartsWithFilter {
    public static void main(String[] args) {
        Path tests = Paths.get("src/test");
        Path[] files = {Paths.get("src/test/AppTest.java"), Paths.get("src/testdata/users.csv"),
                        Paths.get("src/main/App.java"), Paths.get("src/test/util/Fake.java")};
        for (Path f : files) {
            boolean byPath = f.startsWith(tests);
            boolean byText = f.toString().startsWith(tests.toString());
            System.out.println(f.getFileName() + ": path=" + byPath + ", text=" + byText);
        }
    }
}

How It Works

  1. Same separators on both sides. The text check compares f.toString() with tests.toString(), so both use the native separator and the comparison is fair on every system.
  2. The false positive. src/testdata/users.csv begins with the characters src/test, so the text check says true, while the Path check sees testdata is not test.
  3. Any depth below the prefix. Fake.java sits one folder deeper, in src/test/util, and still starts with src/test; only the first two names have to match.

Frequently Asked Questions

Path.startsWith compares whole name elements and the root, so /home/anna does not start with /home/an. String.startsWith compares characters and would return true.
Normalize the path and call path.startsWith(folder), with both paths absolute or both relative. For files on disk, compare toRealPath() results so symbolic links cannot escape.
No. It compares the path as written. Call normalize() first, otherwise /base/../etc still starts with /base.
On Linux and macOS, yes. On Windows, names are compared without regard to case.
Yes. startsWith(String) converts the text to a path of the same file system first. It throws InvalidPathException if the text is not a valid path.

Next: Path.subpath()

Take a range of name elements out of a path as a new relative path.

subpath() 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.

14 people found this page helpful