【问题标题】:How to read files with specific type of files from subfolders of a directory in JAVA如何从JAVA目录的子文件夹中读取具有特定类型文件的文件
【发布时间】:2023-04-05 09:57:01
【问题描述】:

我想问一下如何从目录中存在的子文件夹中读取 (.xxx) 类型的文件。

我有一个包含子文件夹的文件夹(子文件夹的数量未知)

  C:\MainFolder  
  contains->           [subFolder_A][subFolder_B]......[subFolder_n]

每个子文件夹都包含大量文件,但其中一个具有不同的类型,特别是 (.fingerprint) 类型。

       [subFolder_A]  -->  a.txt , atitle.txt  , afin.fingerprint
       [subFolder_B]  -->  b.txt , btitle.txt  , bfin.fingerprint
             ...............................................
       [subFolder_n]  -->  n.txt , ntitle.txt  , nfin.fingerprint

所以我想每次将此文件中的一个读取到 java ...执行一些功能,然后执行下一个,直到 C:\MainFolder 完成扫描。

如果我直接给出代码的路径,我可以阅读一个,但如果有人知道用自动方式把它们全部拿走,我想要一些提示

        Path path = Paths.get("C:\\MainFolder\\afin.fingerprint");
        byte[] data;
        byte[] fin;
        try {
             this.data = Files.readAllBytes(path);
             byte[] data = Files.readAllBytes(path);
       } catch (Exception e) {....}
          fin=data;

【问题讨论】:

    标签: java file subdirectory


    【解决方案1】:

    你可以walk the file tree recursively with a stream,比如这样:

     Files.walk(Paths.get("C:/MainFolder"))
          .filter(p -> p.toFile().isFile())
          .filter(p -> p.getFileName().toString().endsWith(".fingerprint"))
          .forEach(p -> process(p));
    

    【讨论】:

    • 对不起是getFileName - 并且process是你需要写的方法!
    • 尝试 { Files.walk(Paths.get("C:\\MainFolder")) .filter(p -> p.toFile().isFile()) .filter(p -> p .getFileName().endsWith(".fingerprint")) .forEach(p -> process(p)); } catch (IOException ex) { Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex); } } static void process(Path p) { System.out.println("找到的文件"+p.getName); } 类似的东西没有用..实际上我会调用一个函数而不是 print(打印是为了看看它是否找到)
    • 当我运行我提前发布的代码时,它运行时没有任何警告,但我没有看到 Mainfolder [System.out.println("Found file"+p.getName) 的子文件夹中包含的文件名; ]
    • @NakosKotsanis 将第二个过滤器更改为.filter(p -> p.getFileName().toString().endsWith(".fingerprint")),现在应该可以了。
    【解决方案2】:

    您可以找到主文件夹的所有子文件夹并循环扫描它们。对于每个子文件夹,您可以再次找到其中的所有文件,然后根据需要过滤它们。 要列出文件夹的内容,请使用 https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()

    【讨论】:

      【解决方案3】:

      你可以像这样遍历子目录:

      File directory = new File(//path to directory);
        for(File subdirectory : directory.listFiles()){
          for(File file : Subdirectory.listFiles()){
            if(file.toString().endsWith(".footprint"){
            //doStuff
          }
        }
      }
      

      【讨论】:

      • 嗨 Nakos,我已编辑代码以从主目录开始。在这种情况下,您所要做的就是提供子目录目录的第一个路径。希望对您有所帮助。
      猜你喜欢
      • 2013-02-28
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2014-01-22
      • 2011-10-09
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多