统计代码行数(正则表达式)

package com.yonge.test;

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

public class Test {

	private static int commen, white, normal;

	public Test() {
	}

	private static void countCode(File file) {
		// 判断是否是.java结尾的文件
		if (file.getName().matches(".*\\.java$")) {
			FileReader fr = null;
			BufferedReader br = null;
			try {
				fr = new FileReader(file);
				br = new BufferedReader(fr);
				String lineContent;
				boolean isCommen = false;
				try {
					while (br.ready()) {
						// 由于可能头存在空格,我们加trim()方法
						lineContent = br.readLine().trim();
						// 先判断注释行
						if (lineContent.matches("^//.*")) {
							commen++;
						} else if (lineContent.matches("^/\\*.*")
								&& !lineContent.matches(".*\\*/$")) {
							commen++;
							isCommen = true;
						} else if (isCommen) {
							commen++;
							if (lineContent.matches(".*\\*/$")) {
								isCommen = false;
							}
						} else if (lineContent.matches("^/\\*.*")
								&& lineContent.matches(".*\\*/$")) {
							commen++;
						}
						// 判断空白行
						else if (lineContent.matches("^[\\s && [^\\n]]*$")) {
							white++;
						} else {
							normal++;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				System.out.println("文件【" + file.getAbsolutePath() + "】不存在");
			} finally {
				if (br != null) {
					try {
						br.close();
						if (fr != null) {
							fr.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static void main(String[] args) {

		String filePath = "C:\\Users\\yonge\\workspace\\regex";
		File file = new File(filePath);
		File[] files = file.listFiles();
		if (files != null && files.length > 0) {
			for (File f : files) {
				readDirectory(f);
			}
		}
		System.out.println("空白行数:" + white);
		System.out.println("注释行数:" + commen);
		System.out.println("有效行数:" + normal);
	}

	/**
	 * 递归目录
	 * @param file
	 */
	private static void readDirectory(File file) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File f : files) {
				readDirectory(f);
			}
		} else {
			countCode(file);
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值