方法一:
1 package pers.stresm; 2 3 import java.io.File; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 /** 8 * 统计一个目录下,所有的类型及不同类型的个数 E:webjavascript 9 * 方法(一) 10 * @author three 11 * 12 */ 13 public class AllFilesInfo2 { 14 15 static Map<String, Integer> map = new HashMap<>(); 16 17 public static void show(File dir) { 18 for (File ff : dir.listFiles()) { 19 if (ff.isDirectory()) { 20 show(ff); 21 } else if (ff.isFile()) { 22 String n = ff.getName(); 23 int pos = n.lastIndexOf("."); 24 String ext = pos == -1 ? "未知 " : "." + n.substring(pos + 1); 25 if (map.containsKey(ext)) { 26 map.put(ext, map.get(ext) + 1); 27 } else { 28 map.put(ext, 1); 29 } 30 31 } 32 } 33 } 34 35 public static void main(String[] args) { 36 show(new File("E:\web\javascript")); 37 map.forEach((k, v) -> { 38 System.out.printf("%-6s=%d ", k, v); 39 }); 40 } 41 42 }
方法二:
1 package pers.stresm; 2 3 import java.io.File; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 /** 8 * 统计一个目录下,所有的类型及不同类型的个数 E:webjavascript 9 * 方法(二) 10 * @author three 11 * 12 */ 13 public class AllFilesInfo { 14 15 static Set<String> setExt = new HashSet<>(); 16 static int num = 0; 17 18 /** 19 * 获取当前目录下的所有后缀名 20 * @param f 21 */ 22 public static void getExt(File dir) { 23 for(File e : dir.listFiles()) { 24 if(e.isDirectory()) { 25 getExt(e); 26 }else { 27 //将获取的后缀名存入set集合 28 setExt.add("."+e.getName().substring(e.getName().lastIndexOf(".")+1)); 29 } 30 } 31 } 32 33 /** 34 * 获得后缀名对应的数量 35 * @param f 36 * @param suffix 37 */ 38 public static void extCount(File file,String ext) { 39 for(File e : file.listFiles()) { 40 if(e.isDirectory()) { 41 extCount(e,ext); 42 }else if(e.getName().endsWith(ext)) { 43 ++num; 44 } 45 } 46 } 47 48 public static void main(String[] args) { 49 File file = new File("E:\web\javascript"); //需要统计的目录路径 50 51 getExt(file); //获取后缀名集合 52 53 String str = ""; 54 55 for(String e : setExt) { //遍历每一个后缀 56 str = String.format("%8s = ", e); //格式化 57 System.out.print(str); 58 59 num = 0; 60 61 extCount(file,e); //统计后缀名数量 62 System.out.println(num); 63 } 64 } 65 }