Java通过IO流获得指定目录下所有文件

没有废话只有代码,复制粘贴即可使用

package com.lfs;

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

public class GetAllFile {

    private static Map<String,Map<String,Long>> map = new HashMap();

    //获得指定目录下所有文件
    public static void main(String[] args) {
        File file = new File("F:");
        findPath(file);
        for(Map.Entry<String, Map<String, Long>> each : map.entrySet()){
            Map<String, Long> temp = each.getValue();
            String path = null;
            Long mem = 0L;
            for(Map.Entry<String,Long> m : temp.entrySet()){
                path = m.getKey();
                mem = m.getValue();
            }
            mem = mem / (1024*1024);//返回的文件大小单位是Byte,即字节,需要换算成MB,对应关系为1024B = KB,1024KB = 1MB
            if(mem > 300)
            System.out.println("\t大小:\t"+ mem + "MB"
                    +"\t\t\t\t文件名:\t"+ each.getKey()  + "\t\t\t\t路径:\t"+ path);
        }
    }

    //递归寻找
    public static void findPath(File f){
        if(f != null){
            //获得文件夹下面的所有文件和文件并且返回File数组
            File[] files = f.listFiles();
            if(files != null){
                for(File file : files) {
                    if (file.isFile()) {//如果是文件那么就操作
                        Map<String, Long> temp = new HashMap();
                        temp.put(file.getAbsolutePath(), file.length());//存入绝对文件路径和文件大小
                        map.put(file.getName(), temp);//文件名和封装好的map对象
                    } else {
                        //不是文件那么说明是文件夹,继续递归往后找
                        if(file != null)
                            findPath(file);
                    }
                }
            }

        }

        return ;
    }


}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值