Java Path name components
Read individual names and ranges from a hierarchical path.
A simple example
Path name components
- Start with Path notes/a.txt
- Do this Read its final component
- Result a.txt
Syntax
Path getFileName()
JDK 21 declarations (6)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaOrganize submitted projects by year
A department receives a relative path containing a year, a course and a report. The clerk needs the report name for the receipt and the first two names for filing.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path item = Path.of("2026", "biology", "pond.csv");
System.out.println(item.getFileName());
System.out.println(item.getParent().equals(item.subpath(0, 2)));
System.out.println(item.getName(0));
}
}
pond.csv true 2026
The first name is at index zero. The parent of this three-name path covers the first two names.
Build breadcrumbs for a folder browser
A student opens a nested project folder on a tablet. The browser needs one breadcrumb per name and a total for the screen reader, even when the system uses a different separator.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path item = Path.of("lab", "week1", "results");
System.out.println(item.getNameCount());
var parts = item.iterator();
while (parts.hasNext()) System.out.println(parts.next());
}
}
3 lab week1 results
Iteration yields the names in order and omits any root component.
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
What to watch for
The root is separate from the names. A one-name relative path has no parent, and the end index of subpath is exclusive.