5

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!

Warweedy
  • 53
  • 1
  • 1
  • 4
  • 1
    What do you mean 1 folder deeper, you need to specify in which folder you want to go. – nick zoum Oct 12 '16 at 08:34
  • Have you tried http://stackoverflow.com/questions/30088245/java-7-nio-list-directory-with-wildcard – kjsebastian Oct 12 '16 at 08:36
  • Will try & edited for clarity – Warweedy Oct 12 '16 at 08:40
  • @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 stream = Files.newDirectoryStream(path, "/*/test.zip"); File input = new File(stream);` Since stream is not a String i cant get the file to work. – Warweedy Oct 12 '16 at 08:54
  • @Warweedy You have to learn to look harder in the api docs. :) If any one else having similar issues.: https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html shows how to get a `Path` from the stream. And from the `Path` you can retrieve the `File` using `toFile()`. Docs are your friend. – kjsebastian Oct 12 '16 at 10:22

4 Answers4

5

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());
David SN
  • 3,389
  • 1
  • 17
  • 21
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")
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
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;
}
John
  • 3,458
  • 4
  • 33
  • 54
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());
siarheib
  • 159
  • 1
  • 8