How to check the extension of a Java 7 Path

JavaPathJava 7

Java Problem Overview


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 Solutions


Solution 1 - 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.

Solution 2 - Java

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

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

Solution 4 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThunderforgeView Question on Stackoverflow
Solution 1 - JavafanView Answer on Stackoverflow
Solution 2 - JavaMiserable VariableView Answer on Stackoverflow
Solution 3 - JavaPero122View Answer on Stackoverflow
Solution 4 - JavaMarkView Answer on Stackoverflow