统计java代码行数

package datasturct;

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

public class CodeCounter {
	/**普通行数*/
	private long normalLines=0;
	/**注释行数*/
	private long commentLines=0;
	/**空白行数*/
	private long spaceLines=0;
	/**总行数*/
	private long totalLines=0;
	/***
	 * 通过java文件路径构造该对象
	 * @param filePath java文件路径
	 */
	public CodeCounter(String filePath){
		tree(filePath);
	}
	/**
	 * 处理文件的方法
	 * @param filePath 文件路径
	 */
	private void tree(String filePath){
		File file=new File(filePath);
		File[] childs=file.listFiles();
		if(childs==null){
			parse(file);
		}else{
		for(int i=0;i<childs.length;i++){
			System.out.println("path:"+childs[i].getPath());
			if(childs[i].isDirectory()){
				tree(childs[i].getPath());
			}else{
				childs[i].getName().matches(".*\\.java$"); 
				System.out.println("当前"+childs[i].getName()+"代码行数:");
				parse(childs[i]);
				getCodeCounter();
			}
		}
		}
	}
	/**
	 * 解析文件
	 * @param file 文件对象
	 */
	private void parse(File file){
		BufferedReader br=null;
		boolean comment=false;
		try {
			br=new BufferedReader(new FileReader(file));
			String line="";
			while((line=br.readLine())!=null){
				line=line.trim();//去除空格
				if(line.matches("^[\\s&&[^\\n]]*$")) {   
					   spaceLines ++;   
				}else if((line.startsWith("/*"))&& !line.endsWith("*/")) {   
					   commentLines ++;   
					   comment = true;   
	            }else if(true == comment) {   
			           commentLines ++;   
	            if(line.endsWith("*/")) {   
					   comment = false;   
					   }   
				}else if(line.startsWith("//")) {   
					    commentLines ++;   
				}else {   
					   normalLines ++;   
			          } 
			  }
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 得到Java文件的代码行数
	 */
	private void getCodeCounter(){
		totalLines=normalLines+spaceLines+commentLines;
		System.out.println("普通代码行数:"+normalLines);
		System.out.println("空白代码行数:"+spaceLines);
		System.out.println("注释代码行数:"+commentLines);
		System.out.println("代码总行数:"+totalLines);
		normalLines=0;
		spaceLines=0;
		commentLines=0;
		totalLines=0;
	}
	public static void main(String args[]){
		CodeCounter counter=new CodeCounter("d:\\newapps\\workspace\\Util\\src");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值