Search code examples
javafilelambdapathdirectorystream

Java - Count all file extensions in a folder using DirectoryStream


I would like to show all file extensions in a specific folder and give the total for each extension using DirectoryStream.

Now I'm only showing all the files in that folder, but how do I get their extensions only instead? I should also get the extensions of these files and count the total for each extension in that folder (see output below).

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.");
    }
}

The output should look like this. I suppose the best way to get this output is using lambdas?

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

Solution

  • First check whether it is a file, if so extract the file name extension. Finally use the groupingBy collector to get the dictionary structure you want. Here's how it looks.

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