Java - 使用 DirectoryStream 计算文件夹中的所有文件扩展名

Java - Count all file extensions in a folder using DirectoryStream

我想显示特定文件夹中的所有文件扩展名,并使用 DirectoryStream 给出每个扩展名的总数。

现在我只显示该文件夹中的所有文件,但我如何才能只显示它们的扩展名? 我还应该获取这些文件的扩展名并计算该文件夹中每个扩展名的总数(见下面的输出)。

public static void main (String [] args) throws IOException {

    Path path = Paths.get(System.getProperty("user.dir"));

    if (Files.isDirectory(path)){
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path);

        for (Path p: directoryStream){
            System.out.println(p.getFileName());
        }
    } else {
        System.out.printf("Path was not found.");
    }
}

输出应如下所示。 我想获得此输出的最佳方法是使用 lambdas?

FILETYPE    TOTAL
------------------
CLASS    |  5
TXT      |  10
JAVA     |  30
EXE      |  27

首先检查是否是文件,如果是则提取文件扩展名。最后使用groupingBy收集器得到你想要的字典结构。这是它的样子。

try (Stream<Path> stream = Files.list(Paths.get("path/to/your/file"))) {
    Map<String, Long> fileExtCountMap = stream.filter(Files::isRegularFile)
        .map(f -> f.getFileName().toString().toUpperCase())
        .map(n -> n.substring(n.lastIndexOf(".") + 1))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

您可以尝试这样的操作:

public class FileCount {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get(System.getProperty("user.dir"));

        if (Files.isDirectory(path)) {

            Map<String, Long> result = Files.list(path).filter(f -> f.toFile().isFile()).map(FileCount::getExtension)
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

            System.out.println(result);
        } else {
            System.out.printf("Path was not found.");
        }

    }

    public static String getExtension(Path path) {
        String parts[] = path.toString().split("\.");
        if (1 < parts.length) {
            return parts[parts.length - 1];
        }

        return path.toString();
    }

您甚至可以 return 地图并按照您想要的方式排列结果。