我想在一个特定的文件夹中显示所有文件扩展名,并使用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发布于 2019-03-30 17:10:45
首先检查它是否是一个文件,如果是,请提取文件扩展名。最后,使用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()));
}发布于 2019-03-30 17:29:50
你可以试试这样的东西:
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();
}您甚至可以返回Map并以您想要的方式排列结果。
https://stackoverflow.com/questions/55433557
复制相似问题