Count the number of all file types in a directory, including subdirectories.
There are detailed explanations in the code, if you don't understand, please leave a message.
public class StatisticalFileType {
//创建一个Map集合,将所得到的文件类型放入集合中,Key对应文件类型,Value对应文件出现的次数
static Map<String, Integer> map = new HashMap<>();
public static void main(String[] args) {
//调用type方法,并输入你要统计目录的地址
type(new File("e:/INFP"));
//输出map的个数
System.out.println(map.size());
//foreach遍历输出
for (String s:map.keySet()){
System.out.println(s+"="+map.get(s));
}
}
public static void type(File file){
//判断文件是否为目录是目录则进行遍历递归
if (file.isDirectory()){
for (File ff:file.listFiles()){
if (ff.isDirectory()){
type(ff);
}
//如果是文件,则先获得文件的名字
else if (ff.isFile()) {
//未知文件类型
String sst="未知类型";
//获得文件名
String st=ff.getName();
//如果文件中包含"."
if (st.contains(".")){
//截取st中的最后一次出现的"."包含"."以后的内容并赋值给sst
sst=st.substring(st.lastIndexOf("."));
}
//判断,如果集合中K值包含sst,则放进去并把对应的value+1
if (map.containsKey(sst)){
map.put(sst,map.get(sst)+1);
}
//否则,K值没有出现过,则放入集合,value值为1
else {
map.put(sst,1);
}
}
}
}
//和里面的内容一样。如果刚开始判断的是文件,则就直接获取文件的的类型赋予sst后就直接走else语句了
else if (file.isFile()) {
String sst="未知类型";
String st=file.getName();
if (st.indexOf(".")!=-1){
sst=st.substring(st.lastIndexOf("."));
}if (map.containsKey(sst)){
map.put(sst,map.get(sst)+1);
}else {
map.put(sst,1);
}
}
}
}
renderings