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
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.