Java Path.startsWith and endsWith
Match whole initial or final path components.
A simple example
Path.startsWith and endsWith
- Start with Path notes/a.txt
- Do this Test the initial folder name
- Result Matches notes
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.javaRoute 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.
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"));
}
}
true false true
The old folder has a different first name. The filename test matches the complete final name.
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.
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"));
}
}
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?
What to watch for
These tests use provider rules for name comparison. A filename extension is only part of a name.