给定一个文件目录的路径,写一个函数统计这个目录下所有的文件数量并返回。隐藏文件也算,但是文件夹不算 。

题目描述

给定一个文件目录的路径,写一个函数统计这个目录下所有的文件数量并返回。隐藏文件也算,但是文件夹不算 。

栈实现和堆实现(方法都一样)

import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class CountFiles {
    // 注意这个函数也会统计隐藏文件
    //栈实现
    public static int getFileNumber(String folderPath) {
        File root = new File(folderPath);
        if (!root.isDirectory() && !root.isFile()) {
            return 0;
        }
        if (root.isFile()) {
            return 1;
        }
        Stack<File> stack = new Stack<>();
        stack.add(root);
        int files = 0;
        while (!stack.isEmpty()) {
            File folder = stack.pop();
            for (File next : folder.listFiles()) {
                if (next.isFile()) {
                    files++;
                }
                if (next.isDirectory()) {
                    stack.push(next);
                }
            }
        }
        return files;
    }

    //堆实现
    public static int getFileNumber2(String folderPath) {
        File root = new File(folderPath);
        if (!root.isDirectory() && !root.isFile()) {
            return 0;
        }
        if (root.isFile()){
            return 1;
        }
        Queue<File> queue = new LinkedList<>();
        queue.add(root);
        int files = 0;
        while (!queue.isEmpty()){
            File folder = queue.poll();
            for (File next : folder.listFiles()) {
                if (next.isFile()){
                    files++;
                }
                if (next.isDirectory()){
                    queue.add(next);
                }
            }
        }
        return files;
    }

    public static void main(String[] args) {
        // 你可以自己更改目录
        String path = "F:\\算法";
        System.out.println(getFileNumber(path));
        if (getFileNumber(path) == getFileNumber2(path)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Knight_AL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值