Document

编写程序,使用递归方法,实现统计项目目录下有多个java文件,共有多少行代码

import java.io.File;
import java.io.FileInputStream;

/**
 * @author Mxhlin
 * @Email fuhua277@163.com
 * @Date 2022/09/21/14:55
 * @Version
 * @Description
 */
public class Count {
    static int  num=0;
    static int  rows=0;
    public static void main(String[] args) {
        count(new File("D:\\peixun\\java\\Lx"));
        System.out.println("=========================================");
        System.out.println("共有"+num+"个java文件");
        System.out.println("共有"+rows+"行");
    }

    public static void count(File src){
        if (src.isDirectory()){
            File[] files = src.listFiles();
            for (File file : files) {
                if (file.isDirectory()) count(file);
                if (file.isFile() && file.getName().endsWith(".java")){
                    ++num;
                    rows+=getFileRows(file);
                    System.out.printf("文件:%s(%d行)。%n",file.getAbsolutePath(),getFileRows(file));
                }
            }
        }
    }
    public static int getFileRows(File src){
        int rows = 0;
        try (FileInputStream fis = new FileInputStream(src)){
            rows = (int)new String(fis.readAllBytes()).lines().count();
        }catch (Exception e){

        }
        return rows;
    }
}

代码分析
代码的作用是在指定文件夹下找到有多少.java文件,每个java文件又有多少行代码,一共写了多少代码
大家可以使用这个代码来查看自己写了多少代码。注意文件路径一定要对!
写了两个方法分别是getFileRowscount
getFileRows使用FileInputStream文件输入字符流,使用randAllBytes()方法获取文件的所有字节,转化为字符串,获取lines()行和count()计数。转换为int类型,方便计数。最后返回行数!
count遍历所有文件。

posted @   一蓑烟雨任平生。。  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
Document
点击右上角即可分享
微信分享提示