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 hm = getCount(file); System.out.println(hm); } /* * 作用: * 统计一个文件夹中每种文件的个数 * 参数: * 要统计的那个文件夹 * 返回值: * 用来统计map集合 * 键:后缀名 值:次数 * */ public static HashMap getCount(File file) { //1、定义集合用来统计 HashMap 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 sonMap = getCount(f); //遍历sonMap把里面的值累加到hm当中 Set> entries = sonMap.entrySet(); for (Map.Entry 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; } }