Java: FileSystems.getDefault().getPathMatcher: IllegalArgumentException
I was debugging something in the Apache Pinot code earlier this week and came across the FileSystems.getDefault().getPathMatcher
function, which didn’t work quite how I expected.
The function creates a PathMatcher
that you can use to match against Paths.
I was passing through a value of *.json
, which was then resulting in code similar to this:
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
class Main {
public static void main(String args[]) {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("*.json");
System.out.println(matcher.matches(Path.of("/tmp", "mark.json")));
}
}
I’ve copied that code into Replit and if we run it on there, we’ll see the following exception:
Exception in thread "main" java.lang.IllegalArgumentException
at java.base/sun.nio.fs.UnixFileSystem.getPathMatcher(UnixFileSystem.java:286)
at Main.main(Main.java:5)
exit status 1
After reading the documentation I learnt that the pattern needs to be prefixed with regex:
or glob:
, otherwise it won’t work.
Let’s update the example to do that:
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
class Main {
public static void main(String args[]) {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.json");
System.out.println(matcher.matches(Path.of("/tmp", "mark.json")));
}
}
If we run that again, this time we get a result telling us that the file doesn’t exist:
false
About the author
I'm currently working on real-time user-facing analytics with Apache Pinot at StarTree. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also I co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.