Java之利用流计算某文件夹下代码量

一、统计内容

通过一个递归遍历,计算某文件夹下的代码量,统计内容包括正常行数,注释行数,空行数,总行数

二、代码 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
// 统计代码的有效行数
public class CodeCount {
	static long normalLine = 0; //正常的行数
	static long comentLine = 0; //注释行数
	static long whiteLine = 0;  //空行数
	static long countLine = 0;  //总行数
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//代码文件路径
		File file = new File("E:\\设计模式代码汇总");
//		File file = new File("F:\\MyEclipe 2015\\Workplace\\Java\\src\\com\\java\\week05");
		//得到当前路径下的子目录
		File [] files = file.listFiles();
		tree(file);
		countLine = normalLine +comentLine + whiteLine;
		System.out.println("正常代码:"+normalLine);
		System.out.println("注释代码:"+comentLine);
		System.out.println("空行数:"+whiteLine);
		System.out.println("总行数:"+countLine);
	}
	
	private static void count(File child) {
		FileReader fileReader = null;
		BufferedReader br = null;
		boolean coments = false;
		try {
			fileReader = new FileReader(child);
		    br = new BufferedReader(fileReader);
		    String line = "";
		    while((line=br.readLine())!=null) {
		    	/*
		    	 *  去掉开头和末尾的空格行  防止出现
		    	 *	 注释开始前存在空格而导致没有计入注释行的问题
		    	 *	 注释结尾前存在空格而导致不匹配的问题
		    	 */
		    	line = line.trim();   
		    	if(line.matches("^[\\s&&[^\\n]]*$")) {
		    		whiteLine++;
		    	} else if(line.startsWith("/*")&&!line.endsWith("*/")) {
		    		comentLine++;
		    		coments = true;
		    	} else if(true == coments ) {
		    		comentLine++;
		    		if(line.endsWith("*/"))
		    			coments = false;
		    	}else if(line.startsWith("/*")&&line.endsWith("*/")) {   // 一行以/*开头。以*/结尾 
		    		comentLine++;
		    	} 
		    	else if(line.startsWith("//")) {
		    		comentLine++;
		    	}
		    	else 
					normalLine++;
		    }
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			if(br!=null) {
				try {
					br.close();
					br = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/*
	 * 递归遍历所有java文件
	 */
	public static void tree(File file) {
		File[] childFiles = file.listFiles();
		for(File child : childFiles) {
			if(child.getName().matches(".*\\.java$")) {
				count(child);
				}
			if(child.isDirectory()) {
			   tree(child);
			}
		}
	}
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值