Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the extension of a Java 7 Path

Tags:

java

path

java-7

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?

like image 704
Thunderforge Avatar asked Dec 11 '13 22:12

Thunderforge


People also ask

How do I check for Java extensions?

String fileName = "Test. java"; String extension = Files. getFileExtension(fileName); And, also the Apache Commons IO provides the FilenameUtils class provides the getExtension method to get the extension of the file.


1 Answers

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.

like image 107
fan Avatar answered Sep 25 '22 17:09

fan