需求:
/* * 需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件) * 打印格式如下: * txt:3个 * doc:4个 * jpg:6个 * */
需要统计某个文件夹下的文件个数,这里以D盘为例,需要注意的是,在C盘中某些文件或文件夹是需要管理员权限才可以访问的。
需要用到java中的FIle类以及HashMap集合的内容
package a02dome2.file;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class fileCount {
public static void main(String[] args) {
/*
* 需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件)
* 打印格式如下:
* txt:3个
* doc:4个
* jpg:6个
* */
//定义文件路径
File file = new File("D:\\5e\\5EClient");
//将文件类型和个数返回一个HasMap对象
HashMap<String, Integer> count = getCount(file);
//lambda表达式对HashMap集合进行遍历,得到需要统计文件的个数
count.forEach((k,v)->{
System.out.println(k+":"+v+"个");
});
}
//定义方法对文件进行统计,返回一个HashMap对象
public static HashMap<String,Integer> getCount(File file){
HashMap<String,Integer> map = new HashMap<>();
//将文件用文件数组进行存储,方便对文件或文件夹进行遍历和判断
File[] files = file.listFiles();
if(files != null){
for (File file1 : files) {
if(file1.isFile()){
//当前file1是文件
//获取文件名
String name = file1.getName();
//将文件名用.进行切割并返回String数组
String[] arr = name.split("\\.");
if(arr.length >= 2){
//获取文件的后缀名
String endName = arr[arr.length -1];
//对当前类型的文件进行统计
if(map.containsKey(endName)){
int count = map.get(endName);
count++;
map.put(endName,count);
}else{
map.put(endName,1);
}
}
}else{
//当前file1是文件夹
//递归得到文件夹中的每个文件并存到一个HashMap集合中
HashMap<String,Integer> sonMap = getCount(file1);
//获取sonMap的键值对对象
Set<Map.Entry<String, Integer>> entries = sonMap.entrySet();
//遍历子文件夹下的文件
for (Map.Entry<String, Integer> entry : entries) {
//获取键
String key = entry.getKey();
//获取值
int value = entry.getValue();
//判断文件类型并统计到之前统计的文件个数中
if(map.containsKey(key)){
//如何子文件是之前未存在的文件就新加入到map集合
int count = map.get(key);
count = count + value;
map.put(key,count);
}else{
//如何存在则直接自加
map.put(key,value);
}
}
}
}
}
//返回map
return map;
}
}
运行结果如下: