How to check the extension of a Java 7 Path How to check the extension of a Java 7 Path java java

How to check the extension of a Java 7 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.


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");


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")); // falseSystem.out.println(p.endsWith("HelloWorld.java")); // true