Library contents

Java Path.startsWith and endsWith

Match whole initial or final path components.

A simple example

Path.startsWith and endsWith

  1. Start with Path notes/a.txt
  2. Do this Test the initial folder name
  3. Result Matches notes
Comparing path components distinguishes notes from similarly named folders.

Syntax

Java syntax
boolean startsWith(Path other)
JDK 21 declarations (4)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Route incoming receipts by folder

A clerk imports documents from sales and sales-old folders. Only receipts under the sales component belong in today's batch, and a complete filename identifies the closing receipt.

From the programPath entry = Path.of("sales", "march", "close.csv")
First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path entry = Path.of("sales", "march", "close.csv");
        System.out.println(entry.startsWith(Path.of("sales")));
        System.out.println(Path.of("sales-old", "close.csv").startsWith("sales"));
        System.out.println(entry.endsWith("close.csv"));
    }
}
Output
true
false
true

The old folder has a different first name. The filename test matches the complete final name.

Advertisements

Reject an extension passed as a whole name

A tutor filters files with names that end in a particular extension. Compare the component-based Path test with a string suffix check so the filter uses the test appropriate to the request.

From the programPath report = Path.of("grades", "march.csv")
First output linefalse
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path report = Path.of("grades", "march.csv");
        System.out.println(report.endsWith(".csv"));
        System.out.println(report.getFileName().toString().endsWith(".csv"));
    }
}
Output
false
true

The final component is march.csv, while .csv is a suffix of that component.

Locate a rehearsal score

The choir stores each score inside a season folder. Check the last path component against the filename supplied by the catalogue. Does the complete component match?

Givenspring / alto.txt
Worked resultMatches

What to watch for

These tests use provider rules for name comparison. A filename extension is only part of a name.

Documentation for Path.startsWith and endsWith