如何在 Java 文件路径中使用通配符

How to use a Wildcard in Java filepath

我想知道是否以及如何在路径定义中使用通配符。 我想深入一个文件夹并尝试使用 * 但那不起作用。

我想访问随机文件夹中的文件。文件夹结构是这样的:

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

我尝试了什么:

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

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

提前致谢!

我认为不可能以这种方式使用通配符。我建议你使用这样的方式来完成你的任务:

    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());

使用更新的路径、路径、文件

    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());

请注意,带有 Path path 的 lambda 表达式使用 Path.endsWith 匹配 整个 名称,例如 test1/test.ziptest.zip

16 是要查看的目录树的最大深度。 有一个可变参数选项参数,例如(不)跟随符号链接进入其他目录。

其他条件为:

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

您可以使用 PathMatcher 来使用通配符:

您可以为 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";

FileSysten.getPathMather方法中有关于此模式语法的详细信息。创建 PathMather 的代码可以是:

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

您可以使用 Files.find() 方法找到所有匹配此模式的文件:

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

查找方法returns一个Stream<Path>。您可以对该流进行操作或将其转换为列表。

paths.forEach(...);

或:

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

这是一个完整的示例,说明如何使用 Apache Ant 提供的 DirectoryScanner 实现根据模式从给定文件中获取文件列表。

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;
}