Path startsWith And endsWith Element Compare
startsWith and endsWith on Path compare whole path elements instead of characters, which keeps route matching honest when names share prefixes.
Code
import java.nio.file.Path;
public class PathElementSemantics {
public static void main(String[] args) {
Path log = Path.of("var", "log", "app.log");
// 路径按元素拆解:getNameCount / getName / getFileName / subpath
System.out.println("parts = " + log.getNameCount());
for (int i = 0; i < log.getNameCount(); i++) {
System.out.println(" name[" + i + "] = " + log.getName(i));
}
System.out.println("fileName = " + log.getFileName());
System.out.println("parent = " + log.getParent());
System.out.println("subpath = " + log.subpath(1, 3));
// startsWith/endsWith 按整段 element 比较(compare whole elements),
// 不做字符串前缀匹配:'va' 不是 'var','app' 不是 'app.log'
System.out.println("startsWith(\"var\") = " + log.startsWith("var"));
System.out.println("startsWith(\"va\") = " + log.startsWith("va"));
System.out.println("endsWith(\"app\") = " + log.endsWith(Path.of("app")));
System.out.println("endsWith(\"app.log\") = " + log.endsWith("app.log"));
}
}Elements, not characters
Path.of("var", "log", "app.log") splits into three named elements, and the demo prints them via getNameCount(), getName(i), getFileName(), getParent(), and subpath(1, 3). The decisive part of the file is the second block: startsWith and endsWith on Path compare whole path elements, so "va" is not a prefix of the var element and Path.of("app") is not a suffix of app.log — the file’s comment states both traps explicitly.
The element-wise verdicts
parts = 3
name[0] = var
name[1] = log
name[2] = app.log
fileName = app.log
parent = var/log
subpath = log/app.log
startsWith("var") = true
startsWith("va") = false
endsWith("app") = false
endsWith("app.log") = true
The element-wise verdicts are the opposite of what String.startsWith/String.endsWith would give on the joined string — that honesty is the reason route and permission checks should compare paths element-wise rather than as text.
The line that deconstructs the path
Path log = Path.of("var", "log", "app.log");
Everything after it reads from this three-element structure: the parent is var/log (elements minus the last), the subpath splices elements 1–3, and the file name is just element 2.
Interactive Tools for This Topic
FAQ
- What does Path startsWith And endsWith Element Compare print when run?
- No setup needed: run the file and look for labeled lines like `parts =`, `name[`, `fileName =` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.