[英]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
. 我想显示特定文件夹中的所有文件扩展名,并使用
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?
我想获得此输出的最佳方法是使用lambda?
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. 最后,使用
groupingBy
收集器获取所需的字典结构。 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()));
}
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. 您甚至可以返回地图,并按所需方式排列结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.