java练习-遍历文件,集合练习

需求:

/*
需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件夹)
打印格式如下:
txt:3个
doc:4个
jpg:6个


*/

课堂实例代码:
package com.example.ss_0203_array.test.test_0830;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 * 作用:
 *       统计一个文件夹中每种文件的个数
 * 参数:
 *       要统计的那个文件夹
 * 返回值:
 *       用来统计map集合
 *       键:后缀名 值:次数
 *
 *       a.txt
 *       a.a.txt
 *       aaa(不需要统计的)
 * */
public class test4 {
    public static void main(String[] args) {
        File file = new File("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码");

        HashMap map = getCount(file);

        System.out.println(map);
    }

    private static HashMap getCount(File file) {
        HashMap<String,Integer> hm = new HashMap();

        File[] files = file.listFiles();
        for (File fls : files) {
            if (fls.isFile()){
                String[] arr = fls.getName().split("\\.");
                if(arr.length==1) continue;
                String type = arr[arr.length-1];
                if(hm.containsKey(type)){
                    hm.put(type,(int) hm.get(type) + 1);
                }else{
                    hm.put(type,1);
                }
            }else{
                HashMap<String,Integer> shm = getCount(fls);
                Set<Map.Entry<String, Integer>> entries = shm.entrySet();
                for (Map.Entry<String, Integer> entry : entries) {
                    String key = entry.getKey();
                    int val = entry.getValue();
                    if (hm.containsKey(key)){
                        hm.put(key,hm.get(key)+val);
                    }else {
                        hm.put(key,val);
                    }
                }
            }
        }
        return hm;
    }
}

  个人练习:

package com.example.ss_0203_array.test.test_0830;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
 * 作用:
 *       统计一个文件夹中每种文件的个数
 * 参数:
 *       要统计的那个文件夹
 * 返回值:
 *       用来统计map集合
 *       键:后缀名 值:次数
 *
 *       a.txt
 *       a.a.txt
 *       aaa(不需要统计的)
 * */
public class test2 {
    public static void main(String[] args) {
        File file = new File("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码");

        HashMap<String,Integer> hm = new HashMap();
        Map map = getCount(file, hm);

        System.out.println(map);
    }

    private static Map getCount(File file,HashMap hm) {
        File[] files = file.listFiles();
        for (File fls : files) {
            if (fls.isFile()){
                String[] arr = fls.getName().split("\\.");
                if(arr.length==1) continue;
                String type = arr[arr.length-1];
                if(hm.containsKey(type)){
                    hm.put(type,(int) hm.get(type) + 1);
                }else{
                    hm.put(type,1);
                }
            }else{
                getCount(fls, hm);
            }
        }
        return hm;
    }

}

  

 

 




posted @ 2023-08-30 15:19  庞某人  阅读(11)  评论(0编辑  收藏  举报