键盘录入一个文件夹路径,统计该文件夹(包含子文件夹)中每种类型的文件及个数,注意:用文件类型(后缀名,不包含.(点),如:"java","txt")作为key,
用个数作为value,放入到map集合中,并用两种方式遍历map集合
例如:
doc 的类型的文件有 3 个
java 的类型的文件有 5 个
txt 的类型的文件有 7 个
以下是代码
package cn.itcast.demo5;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class CountFile {
public static void main(String[] args) {
/*
* 创建map,file,传参给count方法
* 设置map初始值
*/
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("docx类型的文件有",0);
map.put("java类型的文件有",0);
map.put("txt类型的文件有",0);
File file = new File("e:\\test");
count(map,file);
entrySetPrint(map);
System.out.println(" ");
keySetPrint(map);
}
public static void count(Map<String,Integer> map,File file){
/*
* 遍历file,判断是否为文件夹,如果不是,则判断是否为docx java txt中的一类,是的话给对应的value+1
* 如果是的话递归调用count方法
*/
for(File f:file.listFiles()){
if(f.isFile()){
if(f.toString().endsWith(".docx"))
//覆盖原有键值对
map.put("docx类型的文件有",map.get("docx类型的文件有")+1);
if(f.toString().endsWith(".java"))
map.put("java类型的文件有",map.get("java类型的文件有")+1);
if(f.toString().endsWith(".txt"))
map.put("txt类型的文件有",map.get("txt类型的文件有")+1);
}else count(map,f);
}
}
/*
* 遍历entry打印map
*/
public static void entrySetPrint(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
/*
* 遍历键打印map
*/
public static void keySetPrint(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key +" "+ map.get(key));
}
}
}