【问题标题】:How to count the number of files in a directory, with the same file extension, in Java?如何在Java中计算目录中具有相同文件扩展名的文件数?
【发布时间】:2019-05-21 13:58:19
【问题描述】:

我希望能够统计用户创建的所有存档游戏。

使用 Java,我如何计算具有特定扩展名的目录中的所有文件?

此代码计算所有文件,无论扩展名如何:

public class MCVE {

    public static void main(String[] args) {
        countFiles();
    }

    private static void countFiles() {
        long amountOfFiles = 0;
        try {
            Stream<Path> files = Files.list(Paths.get("./saves"));
            amountOfFiles = files.count();
            System.out.println(amountOfFiles);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

标签: java file stream filesystems java-stream


【解决方案1】:

在这个函数中传递你的扩展。

amountOfFiles = files.map(Path::toFile).filter(e->e.getName().endsWith(".xml")).count();

【讨论】:

  • 谢谢,但我无法让它工作。它总是返回零。我已经尝试使用我尝试使用的“.sav”文件,以及我放入其中的“.ttf”文件只是为了测试。
  • 确实如此!谢谢!
【解决方案2】:

我已经设法自己解决了。由于不知道如何使用 Path endsWith() 方法,我不得不将每个 Path 对象转换为 String,然后改用 endsWith() 方法的 String 版本。

private static void countFiles() {
    long amountOfFiles = 0;
    try {
        Stream<Path> files = Files.list(Paths.get("./saves"));
        Iterable<Path> iterable = files::iterator;

        String fileName = "";
        for (Path p: iterable) {
            fileName = p.getFileName().toString();
            if(fileName.endsWith(".sav"))
                amountOfFiles++;
        }

        System.out.println(amountOfFiles);

        files.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案3】:

    您可以使用FilenameFilterFileFilter 来过滤您需要的文件或目录。

    File file = new File("pathname");
    // fileter file name start wit Chap
    file.listFiles(pathname -> pathname.getName().startsWith("Chap"));
    // fileter car read file
    file.listFiles(pathname -> pathname.canRead());
    

    可以参考官方文档Java IO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-28
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2010-11-22
      相关资源
      最近更新 更多