Count the number of lines of code in JAVA projects (including comments, blank lines, and the number of java classes)

package com.jmj.common;

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

/**
 * Count the number of lines of code in JAVA projects (including comments, blank lines, and the number of java classes)
 */
public class CountJavaCode {

	static long classcount = 0; // 类数
	static long normalLines = 0; // 空行
	static long commentLines = 0; // comment lines
	static long whiteLines = 0; // lines of code

	public static void main(String[] args) throws Exception {
		File f = new File("D:\\workspace\\dataAudit"); // 目录
		CountJavaCode.treeFile(f);
		System.out.println("路径:" + f.getPath());
		System.out.println("类数:" + classcount);
		System.out.println("空行:" + normalLines);
		System.out.println("注释:" + commentLines);
		System.out.println("代码:" + whiteLines);
	}

	/**
	 * Find all .java files in a directory
	 *
	 * @throws Exception
	 */

	public static void treeFile(File f) throws Exception {
		File[] childs = f.listFiles();
		for (int i = 0; i < childs.length; i++) {
			File file = childs[i];
			if (!file.isDirectory()) {
				if (file.getName().endsWith(".java")) {
					classcount++;
					BufferedReader br = null;
					boolean comment = false;
					br = new BufferedReader(new FileReader(file));
					String line = "";
					while ((line = br.readLine()) != null) {
						line = line.trim();
						if (line.matches("^[//s&&[^//n]]*$")) {
							whiteLines++;
						} 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++;
						}
					}
					if (br != null) {
						br.close();
						br = null;
					}
				}
			} else {
				treeFile(childs[i]);
			}
		}
	}

}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327097580&siteId=291194637