How to use a Wildcard in Java filepath

12,065

Solution 1

I don't think that it's possible to use wildcard in such way. I propose you to use a way like this for your task:

    File orig = new File("\test\orig");
    File[] directories = orig.listFiles(new FileFilter() {
      public boolean accept(File pathname) {
        return pathname.isDirectory();
      }
    });
    ArrayList<File> files = new ArrayList<File>();
    for (File directory : directories) {
        File file = new File(directory, "test.zip");
        if (file.exists())
            files.add(file);
    }
    System.out.println(files.toString());

Solution 2

You can use a wildcardard using a PathMatcher:

You can use a Pattern like this one for your PathMatcher:

/* Find test.zip in any subfolder inside 'origin + folderNames.get(i)' 
 * If origin + folderNames.get(i) is \test\orig\test_1
 * The pattern will match: 
 *  \test\orig\test_1\randomfolder\test.zip     
 * But won't match (Use ** instead of * to match these Paths):
 *  \test\orig\test_1\randomfolder\anotherRandomFolder\test.zip
 *  \test\orig\test_1\test.zip
 */
String pattern = origin + folderNames.get(i) + "/*/test.zip";

There are details about the syntax of this pattern in the FileSysten.getPathMather method. The code to create the PathMather could be:

PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);

You can find all the files that match this pattern using Files.find() method:

Stream<Path> paths = Files.find(basePath, Integer.MAX_VALUE, (path, f)->pathMatcher.matches(path));

The find method returns a Stream<Path>. You can do your operation on that Stream or convert it to a List.

paths.forEach(...);

Or:

List<Path> pathsList = paths.collect(Collectors.toList());

Solution 3

Use the newer Path, Paths, Files

    Files.find(Paths.get("/test/orig"), 16,
            (path, attr) -> path.endsWith("data.txt"))
        .forEach(System.out::println);

    List<Path> paths = Files.find(Paths.get("/test/orig"), 16,
            (path, attr) -> path.endsWith("data.txt"))
        .collect(Collectors.toList());

Note that the lambda expression with Path path uses a Path.endsWith which matches entire names like test1/test.zip or test.zip.

16 here is the maximal depth of the directory tree to look in. There is a varargs options parameter, to for instance (not) follow symbolic links into other directories.

Other conditions would be:

path.getFileName().endsWith(".txt")
path.getFileName().matches(".*-2016.*\\.txt")

Solution 4

Here is a complete example of how to get a list of files from a give file based on a pattern using the DirectoryScanner implementation provided by Apache Ant.

Maven POM:

    <!-- https://mvnrepository.com/artifact/org.apache.ant/ant -->
    <dependency>
        <groupId>org.apache.ant</groupId>
        <artifactId>ant</artifactId>
        <version>1.8.2</version>
    </dependency>

Java:

public static List<File> listFiles(File file, String pattern) {
    ArrayList<File> rtn = new ArrayList<File>();
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setIncludes(new String[] { pattern });
    scanner.setBasedir(file);
    scanner.setCaseSensitive(false);
    scanner.scan();
    String[] files = scanner.getIncludedFiles();
    for(String str : files) {
        rtn.add(new File(file, str));
    }
    return rtn;
}
Share:
12,065
Warweedy
Author by

Warweedy

Updated on June 08, 2022

Comments

  • Warweedy
    Warweedy almost 2 years

    i want to know if and how i could use a Wildcard in a Path definition. I want to go one folder deeper and tried using the * but that doesnt work.

    I want to get to files that are in random folders. Folderstructure is like this:

    \test\orig\test_1\randomfoldername\test.zip
    \test\orig\test_2\randomfoldername\test.zip
    \test\orig\test_3\randomfoldername\test.zip
    

    What i tried:

    File input = new File(origin + folderNames.get(i) + "/*/test.zip");
    
    File input = new File(origin + folderNames.get(i) + "/.../test.zip");
    

    Thank you in advance!