注意1:获取文件后缀命采用split()方法来分割字符串,split(".")这样无法分割,需要换成split("\\.")。
注意2: 使用HashMap来统计次数时,获取HashMap中的Value(次数)进行加1再塞到HashMap中时,请使用hashMap.put(key, ++value)不要使用hashMap.put(key, value++)。
实践代码如下:
public static void main(String[] args) throws IOException {
File file = new File("aaa");
HashMap<String, Integer> hashMap = new HashMap<>();
accountFileTypeNum(file, hashMap);
System.out.println(hashMap);
}
/**
* 统计多级目录中文件类型数量
*
* @param files
* @param hashMap
*/
private static void accountFileTypeNum(File files, HashMap<String, Integer> hashMap) {
if (files.exists()) {
File[] listFiles = files.listFiles();
for (File listFile : listFiles) {
if (listFile.isFile()) {
String[] split = listFile.getName().split("\\.");
if (split.length == 2) {
if (hashMap.containsKey(split[1])) {
Integer n_value = hashMap.get(split[1]);
hashMap.put(split[1], ++n_value);
} else {
hashMap.put(split[1], 1);
}
}
} else {
accountFileTypeNum(listFile, hashMap);
}
}
}
}