Java,搜索给定模式的文件并获取目录名称和完整文件名

时间:2018-10-25 10:26:35

标签: java recursion file-io

我是Java新手。在/ var / data的所有子目录中寻找代码搜索扩展名为.ofg的文件。

所需的输出是

  • 具有包含这些文件的文件的子目录名称
  • 文件的全名
  • 该子目录中那些文件的数量。

有一些可用的教程,但是没有什么适合我的代码库;像

public class FindFiles {

    int inProcThreshold = 0;

    protected File recurfile(File file) {
        File[] dirlist = file.listFiles();

        for (File f : dirlist) {
            if (f.isDirectory()) {
                return f;
            }
        }

        return null;
    }

    protected int numOfInProcs(String location, int level, int maxdepth) {
        File base = new File(location);
        File[] firstlevelfiles = base.listFiles();

        while (level <= maxdepth) {
            for (File afile : firstlevelfiles) {
                if (afile.isDirectory()) {
                    base = recurfile(afile);
                } else {
                    if (afile.getName().endsWith(".txt")) {
                        inProcThreshold++;
                    }
                }
            }
            level++;
        }

        return inProcThreshold;
    }

    public static void main(String[] args) {
        FindFiles test = new FindFiles();
        String dirToList = "I:\\TEST-FOLDER";
        String ext = ".txt";
        int count = test.numOfInProcs(dirToList, 0, 10);
        System.out.println("Number of txt files are " + count);
    }

}

这是我正在尝试的代码,但是它返回0作为输出给我。我正在尝试在I:\ TEST-FOLDER子文件夹中搜索具有extension.txt的文件。

3 个答案:

答案 0 :(得分:0)

使用此过滤器,方法是在dirName参数中提供目录addres,它将列出所有扩展名为.ofg的目录

where right(col1, len(col1) - charindex('~', col1)) > 0 and
      right(col2, len(col2) - charindex('~', col2)) > 0

答案 1 :(得分:0)

我认为您正在寻找的是Files.find。将其传递给谓词,该谓词将检查path.toString()。endsWith(“。ofg”),

它将返回代表匹配文件的Path对象流。您可以通过在此Stream上进行迭代来提取所需的所有数据。

答案 2 :(得分:0)

如果您不需要自己编写递归部分(用于练习或作为任务),则可以将Files#walkFileTreeFileVisitor接口的自定义实现一起使用(@ @ Mena在他的评论中提出)。

扩展SimpleFileVisitor类(或实现FileVisitor接口)并提供要在每个文件上执行的代码:

public class OfgFolderCollectingFileVisitor extends SimpleFileVisitor<Path> {

  /** Stores the matching file paths */
  private final List<Path> collectedPaths = new LinkedList<>();


  @Override
  public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
    // check if the current file is an .ofg file
    if (file.toString().endsWith(".ofg")) {
      // it is -> add it's containing folder to the collection
      this.collectedPaths.add(file.getParent());
    }

    return super.visitFile(file, attrs);
  }


  public List<Path> getCollectedPaths() {
    return this.collectedPaths;
  }

}

然后将您的实现实例传递到Files#walkFileTree并随后检查收集的路径:

final OfgFolderCollectingFileVisitor visitor = new OfgFolderCollectingFileVisitor();

try {
  Files.walkFileTree(Paths.get("/var/data"), visitor);
} catch (final IOException ex) {
  ex.printStackTrace();
  return;
}

// let's see if something matched our criteria

final List<Path> ofgContainers = visitor.getCollectedPaths();

System.out.printf("Files found: %d%n", ofgContainers.size());

if (!ofgContainers.isEmpty()) {
  System.out.printf("%nContaining directories:%n");

  for (final Path ofgContainer : ofgContainers) {
    System.out.printf("- %s%n", ofgContaininer);
  }
}

以下是一些示例输出(是的,folder2 ,它的子文件夹包含一个.ofg文件)

Files found: 3

Containing directories:
- \var\data\folder1\folder1.1
- \var\data\folder2
- \var\data\folder2\folder2.2