How to use a Wildcard in Java filepath
Asked Answered
M

4

6

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!

Mucor answered 12/10, 2016 at 8:29 Comment(5)
What do you mean 1 folder deeper, you need to specify in which folder you want to go.Chesna
Have you tried #30088745Swagsman
Will try & edited for clarityMucor
@conscells Seems like my problem with this is that i cant use the Directory Stream as filePath: Path path = FileSystems.getDefault().getPath(origin + folderNames.get(i)); DirectoryStream<Path> stream = Files.newDirectoryStream(path, "/*/test.zip"); File input = new File(stream); Since stream is not a String i cant get the file to work.Mucor
@Mucor You have to learn to look harder in the api docs. :) If any one else having similar issues.: docs.oracle.com/javase/7/docs/api/java/nio/file/… shows how to get a Path from the stream. And from the Path you can retrieve the File using toFile(). Docs are your friend.Swagsman
S
0

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());
Superpower answered 12/10, 2016 at 9:12 Comment(0)
C
6

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());
Caseose answered 12/10, 2016 at 9:41 Comment(0)
S
2

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")
Sellma answered 12/10, 2016 at 9:36 Comment(0)
D
1

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;
}
Decagram answered 24/8, 2020 at 16:33 Comment(0)
S
0

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());
Superpower answered 12/10, 2016 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.