问题描述
我想检查是否有 路径(在 Java 7 中引入)以某个扩展结束.我像这样尝试了 endsWith()
方法:
Path path = Paths.get("foo/bar.java")if (path.endsWith(".java")){//做东西}
然而,这似乎不起作用,因为 path.endsWith(".java")
返回 false.似乎 endsWith()
方法仅在最终目录分隔符(例如 bar.java
)之后的所有内容都完全匹配时才返回 true,这对于我.
那么如何查看路径的文件扩展名?
Java NIO 的 PathMatcher 提供 FileSystem.getPathMatcher(String syntaxAndPattern):
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");路径文件名 = ...;如果(匹配器.匹配(文件名)){System.out.println(文件名);}
有关详细信息,请参阅查找文件教程.>
I'd like to check if a Path (introduced in Java 7) ends with a certain extension. I tried the endsWith()
method like so:
Path path = Paths.get("foo/bar.java")
if (path.endsWith(".java")){
//Do stuff
}
However, this doesn't seem to work because path.endsWith(".java")
returns false. It seems the endsWith()
method only returns true if there is a complete match for everything after the final directory separator (e.g. bar.java
), which isn't practical for me.
So how can I check the file extension of a Path?
Java NIO's PathMatcher provides FileSystem.getPathMatcher(String syntaxAndPattern):
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");
Path filename = ...;
if (matcher.matches(filename)) {
System.out.println(filename);
}
See the Finding Files tutorial for details.
这篇关于如何检查 Java 7 路径的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!