如何检查 Java7路径的扩展

我想检查一下 路径(在 Java7中引入)是否以某个扩展结束。我尝试了 endsWith()方法,就像这样:

Path path = Paths.get("foo/bar.java")
if (path.endsWith(".java")){
//Do stuff
}

但是,这似乎不起作用,因为 path.endsWith(".java")返回 false。似乎 endsWith()方法只有在最终目录分隔符(例如 bar.java)之后的所有内容都完全匹配的情况下才返回 true,这对我来说是不实际的。

那么我怎样才能检查 Path 的文件扩展名呢?

63792 次浏览

There is no way to do this directly on the Path object itself.

There are two options I can see:

  1. Convert the Path to a File and call endsWith on the String returned by File.getName()
  2. Call toString on the Path and call endsWith on that String.

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 four five character 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.toString().toLowerCase().endsWith(".java");

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.

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 true only if it matches with a subelement of your Path object. For example:

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