Java - Count all file extensions in a folder using DirectoryStream

1.3k Views Asked by At

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
2

There are 2 best solutions below

6
On BEST ANSWER

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

You can try something like this:

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

You can even return the Map and arrange the results in the way you want.