【问题标题】:How to use a Wildcard in Java filepath如何在 Java 文件路径中使用通配符
【发布时间】:2016-10-12 08:29:51
【问题描述】:

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

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

\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");

提前谢谢你!

【问题讨论】:

  • 你的意思是1个文件夹更深,你需要指定你想去哪个文件夹。
  • 为了清晰起见会尝试和编辑
  • @conscells 似乎我的问题是我不能将目录流用作文件路径:Path path = FileSystems.getDefault().getPath(origin + folderNames.get(i)); DirectoryStream<Path> stream = Files.newDirectoryStream(path, "/*/test.zip"); File input = new File(stream); 由于流不是字符串,我无法让文件工作。
  • @Warweedy 你必须学会​​在 api 文档中更加努力。 :) 如果其他人有类似的问题。:docs.oracle.com/javase/7/docs/api/java/nio/file/… 显示如何从流中获取Path。从Path,您可以使用toFile() 检索File。文档是您的朋友。

标签: java file path wildcard filepath


【解决方案1】:

您可以通过 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));

find 方法返回一个Stream&lt;Path&gt;。您可以对该 Stream 进行操作或将其转换为 List。

paths.forEach(...);

或者:

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

【讨论】:

    【解决方案2】:

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

        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")
    

    【讨论】:

      【解决方案3】:

      这是一个完整的示例,说明如何使用 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;
      }
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-14
          • 1970-01-01
          • 2017-01-28
          • 1970-01-01
          • 2012-06-06
          • 1970-01-01
          • 2016-12-19
          相关资源
          最近更新 更多