Java 统计文件夹中每种文件数量
以下是 Java 代码示例,可以实现统计一个文件夹中每种文件的个数并打印:
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class FileCount {
public static void main(String[] args) {
File folder = new File('C:/test'); // 文件夹路径
Map<String, Integer> fileCount = new HashMap<>(); // 用来记录每种文件的个数
// 遍历文件夹中的所有文件
for (File file : folder.listFiles()) {
if (file.isFile()) {
String extension = getFileExtension(file); // 获取文件扩展名
if (fileCount.containsKey(extension)) {
fileCount.put(extension, fileCount.get(extension) + 1); // 已有该扩展名,个数加1
} else {
fileCount.put(extension, 1); // 没有该扩展名,添加到Map中,个数为1
}
}
}
// 打印每种文件的个数
for (Map.Entry<String, Integer> entry : fileCount.entrySet()) {
System.out.println(entry.getKey() + ': ' + entry.getValue());
}
}
// 获取文件扩展名
private static String getFileExtension(File file) {
String fileName = file.getName();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex == -1) {
return ''; // 没有扩展名,返回空字符串
}
return fileName.substring(lastDotIndex + 1).toLowerCase(); // 返回小写的扩展名
}
}
代码中,首先定义了一个File对象,表示要统计的文件夹。然后,使用一个HashMap来存储每种文件扩展名及其出现的次数。代码遍历文件夹中的所有文件,获取每个文件的扩展名,并将扩展名及其出现次数存入HashMap中。最后,代码遍历HashMap,打印每种文件的扩展名及其出现次数。
使用方法:
- 将代码中的文件夹路径替换为实际要统计的文件夹路径。
- 编译并运行代码。
- 控制台将打印出每种文件的扩展名及其出现次数。
示例:
假设文件夹C:/test包含以下文件:
- test.txt
- test.java
- test.jpg
- test.png
运行代码后,控制台将打印以下结果:
txt: 1
java: 1
jpg: 1
png: 1
原文地址: https://www.cveoy.top/t/topic/ogfV 著作权归作者所有。请勿转载和采集!