统计文件的代码

package com;

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

public class CodeCounter {
	static long codeLines = 0;
	static long commentLines = 0;
	static long spaceLines = 0;
	static long classnum = 0;
	static long num = 0;
	
	public static void main(String[] args) {
		
		File f = new File("F:\\JAVA\\javacode\\GBN.java");	//这里的目录要输入你要统计代码的文件夹目录
		if(f.exists()) {
			judge(f);			
		}
				
		System.out.println("实际代码行数为:"+codeLines);
		System.out.println("注释代码行数为:"+commentLines);
		System.out.println("空行行数为:"+spaceLines);
		num = codeLines+commentLines+spaceLines;
		System.out.println("总的行数为:"+num);
		System.out.println("类的数目为:"+classnum);
	}
	
	private static void judge(File f) {
		if(!f.isFile()) {
			File[] fs = f.listFiles();//返回的是一个文件数组   是这个文件下面所有的子文件的pathroad
			for(File child: fs) {     //这是遍历的意思 c++里面也可以这样写
				judge(child);
			}
		}
		if(f.exists()&&f.isFile()) {//this abstract pathname is a normal file
			counter(f);
		}
	}

	private static void counter(File child) {
		
		FileReader fr;  // read file
		try {
			fr = new FileReader(child);
			BufferedReader br = new BufferedReader(fr);//把文件里面的内容缓存到br里面
			String line = "";
			boolean flag = false;
			if(child.getName().matches(".*cpp$")||child.getName().matches(".*java$")||
				child.getName().matches(".*txt$")) {   //任意选择文件格式
				try {
					while((line=br.readLine())!=null) {
						String l = line.trim();//去除前导空字符
						
						if(l.matches(".*class.+")) {//匹配前后均有0~n个字符的含有class字样的行
							classnum++;
						}
						if(l.matches("^[[\\s]&&[^\\n]]*")) {//保证是空行 
							spaceLines++;
						}
						else if(l.startsWith("/*")&&l.endsWith("*/")) {
							commentLines++;
							flag = false;
						}
						else if(l.startsWith("/*")) {
							commentLines++;
							flag = true;
						}
						else if(l.endsWith("*/")) {
							commentLines++;
							flag = false;
						}
						else if(true == flag) {
							commentLines++;
						}
						else if(l.startsWith("//")) {
							commentLines++;
						}
						else {
							codeLines++;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值