Java 文件统计:统计文件夹中每种文件数量
Java 文件统计:统计文件夹中每种文件数量
本教程将使用 Java 代码实现统计文件夹中每种文件类型的数量。
思路
- 使用 Java IO 中的
File类获取文件夹路径。 - 遍历文件夹中的所有文件,使用
HashMap统计每种文件的个数。 - 打印统计结果。
代码实现
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class FileCount {
public static void main(String[] args) {
// 获取文件夹路径
String folderPath = "C:\Users\user\Documents\TestFolder";
File folder = new File(folderPath);
// 判断文件夹是否存在
if (!folder.exists() || !folder.isDirectory()) {
System.out.println("文件夹不存在!");
return;
}
// 统计每种文件的个数
Map<String, Integer> countMap = new HashMap<>();
File[] files = folder.listFiles();
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex != -1) {
String fileExt = fileName.substring(dotIndex + 1);
if (countMap.containsKey(fileExt)) {
countMap.put(fileExt, countMap.get(fileExt) + 1);
} else {
countMap.put(fileExt, 1);
}
}
}
}
// 打印统计结果
for (String key : countMap.keySet()) {
System.out.println(key + ":" + countMap.get(key) + "个");
}
}
}
注意事项
- 在使用
File类处理文件和文件夹时,需要注意文件或文件夹是否存在等情况。 - 在获取文件扩展名时,需要注意文件名中可能包含多个点号的情况,需要取最后一个点号后面的字符串作为扩展名。
原文地址: https://www.cveoy.top/t/topic/of9u 著作权归作者所有。请勿转载和采集!