java原生方式统计某个文件目录下的java工程里所有的java代码的行数

某大厂二面笔试题,java原生代码方式实现统计java代码行数、注释行数、package行数、import行数和空行数。遂稍写了一下,如有更优,欢迎指正

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;



public class CodeCounter {

	static int codeLineCount;//代码行
	static int codeBlackCount;//空白行
	static int codeCommentCount;//注释行数
	static int packageLineCount;//package行数
	static int importLineCount;//import行数
	public static void main(String[] args) throws IOException {
		File file = new File("C:\\Users\\FUBINGBING\\Desktop\\code");
		showAllFileLines(file);
		System.out.println("代码行数:"+ codeLineCount);
		System.out.println("空白行:"+ codeBlackCount);
		System.out.println("注释行数:"+ codeCommentCount);
		System.out.println("package行数:"+ packageLineCount);
		System.out.println("import行数:"+ importLineCount);
		System.out.println("总行数:"+ (codeLineCount + codeBlackCount + codeCommentCount + packageLineCount + importLineCount));
	}
	
	static void showAllFileLines(File dir) throws IOException {
		BufferedReader br = null;
		String s = null;
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if(fs[i].getAbsolutePath().endsWith(".java")) {
				br = new BufferedReader(new FileReader(fs[i]));
				boolean comm = false;
				while((s = br.readLine()) != null) {
					if(s.startsWith("/*") && s.endsWith("*/")) {
						codeCommentCount++;
					}else if(s.trim().startsWith("//")) {
						codeCommentCount++;
					}else if(s.trim().startsWith("/*") && !s.endsWith("*/")) {
						codeCommentCount++;
						comm = true;
					}else if(!s.startsWith("/*") && s.endsWith("*/")) {
						codeCommentCount++;
						comm = false;
					}else if(comm) {
						codeCommentCount++;
					}else if(s.trim().length() < 1) {
						codeBlackCount++;
					}else if(s.split(" ")[0].equals("package")) {
						packageLineCount++;
					}else if(s.split(" ")[0].equals("import")) {
						importLineCount++;
					}else {
						codeLineCount++;
					}
				}
			}
			if(fs[i].isDirectory()) {
				showAllFileLines(fs[i]);
			}
		}
	}
	
}

学无止境,每天进步一点点 ~

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值