如何检查 Java 7 路径的扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20531247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check the extension of a Java 7 Path
提问by Thunderforge
I'd like to check if a Path(introduced in Java 7) ends with a certain extension. I tried the endsWith()
method like so:
我想检查路径(在 Java 7 中引入)是否以某个扩展名结尾。我试过这样的endsWith()
方法:
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.
但是,这似乎不起作用,因为path.endsWith(".java")
返回 false。似乎该endsWith()
方法仅在最终目录分隔符(例如bar.java
)之后的所有内容都完全匹配时才返回 true ,这对我来说不实用。
So how can I check the file extension of a Path?
那么如何检查路径的文件扩展名呢?
采纳答案by fan
Java NIO's PathMatcherprovides FileSystem.getPathMatcher(String syntaxAndPattern):
Java NIO 的PathMatcher提供了FileSystem.getPathMatcher(String syntaxAndPattern):
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");
Path filename = ...;
if (matcher.matches(filename)) {
System.out.println(filename);
}
See the Finding Filestutorial for details.
有关详细信息,请参阅查找文件教程。
回答by Mark
There is no way to do this directly on the Path object itself.
无法直接在 Path 对象本身上执行此操作。
There are two options I can see:
我可以看到两个选项:
- Convert the Path to a File and call endsWith on the String returned by File.getName()
- Call toString on the Path and call endsWith on that String.
- 将 Path 转换为 File 并在 File.getName() 返回的 String 上调用 endsWith
- 在 Path 上调用 toString 并在该 String 上调用 endsWith。
回答by Miserable Variable
The Path
class does not have a notion of "extension", probably because the file system itself does not have it. Which is why you need to check its String
representation and see if it ends with the fourfivecharacter string .java
. Note that you need a different comparison than simple endsWith
if you want to cover mixed case, such as ".JAVA"
and ".Java"
:
该Path
班没有“延伸”的概念,可能是因为文件系统本身不拥有它。这就是为什么您需要检查它的String
表示并查看它是否以四个五个字符的 string 结尾.java
。请注意,endsWith
如果要涵盖混合大小写,例如".JAVA"
and ,则需要与 simple 不同的比较".Java"
:
path.toString().toLowerCase().endsWith(".java");
回答by Pero122
Simple solution:
简单的解决方案:
if( path.toString().endsWith(".java") ) //Do something
You have to be carefull, when using the Path.endsWith method. As you stated, the method will return trueonly if it matches with a subelement of your Path object. For example:
使用 Path.endsWith 方法时,您必须小心。正如您所说,该方法仅在与您的 Path 对象的子元素匹配时才会返回true。例如:
Path p = Paths.get("C:/Users/Public/Mycode/HelloWorld.java");
System.out.println(p.endsWith(".java")); // false
System.out.println(p.endsWith("HelloWorld.java")); // true