0

It looks like these are the ways to get a list of files from Java (from here: Using File.listFiles with FileNameExtensionFilter)

Option 1:

File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

Java 8 Option:

pdfTestDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

Question:

Is there really not a way to use a typical file wildcard expression like "./foo/**/admin/*.txt"? Something like:

File dir = new File("/users/foo/bar");
dir.listFiles("./foo/**/admin/*.txt");

or maybe something like

SomeUtil.listFiles(file, "./foo/**/admin/*.txt");

Similar to:

This question is similar to this Stackoverflow post, however this post doesn't really address the question of the recursive case (e.g. "./../*.txt").

How to use a Wildcard in Java filepath

Also similar to this How to find files that match a wildcard string in Java? (which looks more promising, but also does not ask/answer the question why isn't this part of the Java core implementation).

John
  • 3,458
  • 4
  • 33
  • 54
  • https://stackoverflow.com/a/39995413/133203 for inspiration – Federico klez Culloca Aug 24 '20 at 15:25
  • 1
    Of course there's a way. `listFiles()` just isn't it. – Code-Apprentice Aug 24 '20 at 15:28
  • `dir.listFiles("./foo/**/admin/*.txt");` should cause a compiler error because there is no verwion of `listFiles()` that takes a `String` argument. I suggest checking [the documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html). There is an option that takes `FileFilter` that might be helpful. – Code-Apprentice Aug 24 '20 at 15:31
  • java.io.File is part of Java 1.0, which means it was released in 1995. Use the more modern [java.nio.file.Files](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/nio/file/Files.html) class instead. – VGR Aug 24 '20 at 16:08
  • The solution I ended up using is documented here: https://stackoverflow.com/questions/39993946/how-to-use-a-wildcard-in-java-filepath/63565111#63565111 – John Aug 25 '20 at 13:08

0 Answers0