File size: 2,773 Bytes
0284885 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | package File_Case_package;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class case_demo6 {
public static void main(String[] args) {
/*
需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件夹)
打印格式如下:
txt:3个
doc:4个
jpg:6个
*/
File file = new File("/Users/zhaoxiaoyong/Documents/Java/File_project/File_module/src/rough_draft");
HashMap<String, Integer> hm = getCount(file);
System.out.println(hm);
}
/*
* 作用:
* 统计一个文件夹中每种文件的个数
* 参数:
* 要统计的那个文件夹
* 返回值:
* 用来统计map集合
* 键:后缀名 值:次数
* */
public static HashMap<String, Integer> getCount(File file) {
//1、定义集合用来统计
HashMap<String, Integer> hm = new HashMap<>();
//2、进入file文件夹
File[] files = file.listFiles();
//3、遍历数组
for (File f : files) {
//4、判断,如果是文件,统计
if (f.isFile()) {
// a.txt
String name = f.getName();
String[] arr = name.split("\\.");
if (arr.length >= 2) {
String endName = arr[arr.length-1];
if (hm.containsKey(endName)) {
//存在
int count = hm.get(endName);
count++;
hm.put(endName, count);
} else {
//不存在
hm.put(endName, 1);
}
}
} else {
//5、判断,如果是文件夹,递归
//sonMap里面是子文件中每一种文件的个数
HashMap<String, Integer> sonMap = getCount(f);
//遍历sonMap把里面的值累加到hm当中
Set<Map.Entry<String, Integer>> entries = sonMap.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
String key = entry.getKey();
Integer value = entry.getValue();
if (hm.containsKey(key)) {
//存在
int count = hm.get(key);
count += value;
hm.put(key, count);
} else {
//不存在
hm.put(key, value);
}
}
}
}
return hm;
}
}
|