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
Call
What it does
p.getNameCount()
How many names follow the root.
p.getNameCount() - 1
Index 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
Parameter
Description
(none)
No arguments.
Return Value
Return Value
Description
int
The number of name elements; 0 for a root-only path such as /.
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());
}
}
}
Output
Run with java PathNameCountBasic. The output is the same on Windows, macOS, and Linux.
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.
The root counts as nothing./ is only a root, so its count is 0, which also means it has no valid index for getName.
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 + ")");
}
}
}
Output
Run with java PathNameCountDepth. The output is the same on Windows, macOS, and Linux.
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.
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.
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);
}
}
}
Output
Run with java PathNameCountLimit. The output is the same on Windows, macOS, and Linux.
cat.png -> nameCount=1, accepted
albums/2026/dog.png -> nameCount=3, accepted
a/b/c/d/e.png -> nameCount=5, too deep
a/./b/../c.png -> nameCount=2, accepted
How It Works
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.
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.
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).