Java Path getNameCount() Method

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

Definition

In Java, path.getNameCount() returns the number of name elements in a path. /home/anna/docs/report.txt has 4, docs/report.txt has 2, and the root / has 0, because the root is never counted.

The count tells you which indexes are valid for getName(int) and subpath: from 0 up to getNameCount() - 1. It is computed from the text only.

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

Syntax

Call it with no arguments:

Java
int n = Paths.get("/home/anna/docs/report.txt").getNameCount();   // 4
Path last = path.getName(path.getNameCount() - 1);                   // file name
CallWhat it does
p.getNameCount()How many names follow the root.
p.getNameCount() - 1Index of the last element (the file name).
file.getNameCount() - dir.getNameCount()How many levels file sits below dir.

Since Java 7. Dots count as names: a/./b has 3 elements until you call normalize().

Library declarations
Java
// java.nio.file.Path (interface)
int getNameCount()

Parameters

ParameterDescription
(none)No arguments.

Return Value

Return ValueDescription
intThe number of name elements; 0 for a root-only path such as /.

Compare with Similar Methods

Methods that work with the element count:

MethodHow it differs
getName(int)Reads one element; valid indexes are 0 to count - 1.
iterator()Returns exactly getNameCount() elements.
getRoot()The part that is never included in the count.

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 — Count the Name Elements of Different Paths

See the count for an absolute path, a relative path, a single name, the root, and the empty path.

Java
import java.nio.file.Paths;

public class PathNameCountBasic {
    public static void main(String[] args) {
        String[] inputs = {"/home/anna/docs/report.txt", "docs/report.txt", "report.txt", "/", ""};
        for (String s : inputs) {
            System.out.println("\"" + s + "\" -> " + Paths.get(s).getNameCount());
        }
    }
}

How It Works

  1. Names, not slashes. The absolute path has four slashes and four names, but the count comes from the names: home, anna, docs, and report.txt.
  2. The root counts as nothing. / is only a root, so its count is 0, which also means it has no valid index for getName.
  3. The empty path counts as one. Paths.get("") is defined as a path with one empty name element, so it reports 1; test for it with toString().isEmpty() when that matters.

Example 2 — Show How Deep Each File Sits in a Project

Subtract the name count of the project folder from each file's count to get its depth, and indent the file name by that many steps.

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

public class PathNameCountDepth {
    public static void main(String[] args) {
        Path base = Paths.get("projects/shop");
        Path[] files = {Paths.get("projects/shop/README.md"),
                        Paths.get("projects/shop/src/App.java"),
                        Paths.get("projects/shop/src/main/java/Main.java")};
        for (Path f : files) {
            int depth = f.getNameCount() - base.getNameCount() - 1;
            StringBuilder indent = new StringBuilder();
            for (int i = 0; i < depth; i++) {
                indent.append("  ");
            }
            System.out.println(indent.toString() + f.getFileName() + " (depth " + depth + ")");
        }
    }
}

How It Works

  1. Counts, not text. The base has 2 names; README.md has 3, App.java 4, and Main.java 6, so the depth is computed with plain integer subtraction.
  2. Minus one for the file itself. The extra - 1 removes the file name from the count, so a file directly inside shop has depth 0 and Main.java, three folders down, has depth 3.
  3. OS-neutral output. Only file names and numbers are printed, so the indented tree looks the same on Windows; the subtraction assumes every file really starts with the base, which startsWith can confirm.

Example 3 — Reject Upload Paths That Are Nested Too Deeply

An upload form accepts at most two folders plus a file name. Check getNameCount() after cleaning the path with normalize().

Java
import java.nio.file.Paths;

public class PathNameCountLimit {
    static final int MAX_NAMES = 3;

    public static void main(String[] args) {
        String[] uploads = {"cat.png", "albums/2026/dog.png", "a/b/c/d/e.png", "a/./b/../c.png"};
        for (String u : uploads) {
            int count = Paths.get(u).normalize().getNameCount();
            String verdict = count <= MAX_NAMES ? "accepted" : "too deep";
            System.out.println(u + " -> nameCount=" + count + ", " + verdict);
        }
    }
}

How It Works

  1. A simple limit. MAX_NAMES allows two folders plus the file name; the original upload text is printed, so the lines look identical on every system.
  2. Normalize before counting. a/./b/../c.png has five raw elements, but after normalize() only a and c.png remain, so it is counted as 2 and accepted.
  3. Counting is not a security check. The count limits nesting only; to stop ../ from escaping the upload folder, also resolve against the base and test it with startsWith.

Frequently Asked Questions

The number of name elements in the path, without the root. /home/anna/report.txt returns 3 and docs/report.txt returns 2.
The path / consists only of a root, and the root is not a name element.
The empty path is defined as a path with one name element that is empty. It is the only path whose single name is an empty string.
Yes. They are ordinary name elements until you call normalize(), which removes them where possible.
Subtract the counts: file.getNameCount() - folder.getNameCount(). Normalize both paths first and check file.startsWith(folder).

Next: Path.getParent()

Get the folder part of a path, or null when there is none.

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

13 people found this page helpful