Library contents

Java Path name components

Read individual names and ranges from a hierarchical path.

A simple example

Path name components

  1. Start with Path notes/a.txt
  2. Do this Read its final component
  3. Result a.txt
The directory portion is notes and the last name is a.txt.

Syntax

Java 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.java

Organize 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.

From the programPath item = Path.of("2026", "biology", "pond.csv")
First output linepond.csv
Main.java
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));
    }
}
Output
pond.csv
true
2026

The first name is at index zero. The parent of this three-name path covers the first two names.

Advertisements

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.

From the programPath item = Path.of("lab", "week1", "results")
First output line3
Main.java
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());
    }
}
Output
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.

Givenspring / alto.txt
Worked resultalto.txt

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.

Documentation for Path name components