📄 codecounter(代码行数统计工具类).java
字号:
package javatools.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class CodeCounter {
//有效行数
private static long normalLines = 0;
//注释行数
private static long commentLines = 0;
//空白行
private static long whiteLines = 0;
private ArrayList<File> al = new ArrayList<File>();
/**
* 递归找到该目录下的所有java源文件
* @param homeDir
*/
public void findJavaSource(File homeDir) {
if(homeDir.isFile()){
al.add(homeDir);
return;
}
File[] f = homeDir.listFiles();
for (File child : f) {
if (child.isFile() && child.getName().matches(".*\\.java$")) {
al.add(child);
} else if (child.isDirectory()) {
findJavaSource(child);
}
}
}
public static void main(String []str){
CodeCounter cc = new CodeCounter();
//测试时别忘了该目录地址
File homeDir = new File("H:\\JSP\\webapps\\Test\\src");
cc.count(homeDir);
}
public void count(File homeDir) {
this.findJavaSource(homeDir);
for (File child : al) {
parse(child);
}
System.out.println("normalLines:" + normalLines);
System.out.println("commentLines:" + commentLines);
System.out.println("whiteLines:" + whiteLines);
}
private static void parse(File f) {
BufferedReader br = null;
boolean comment = false;
try {
br = new BufferedReader(new FileReader(f));
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 (line.startsWith("/*") && line.endsWith("*/")) {
commentLines++;
} else if (true == comment) {
commentLines++;
if (line.endsWith("*/")) {
comment = false;
}
} else if (line.startsWith("//")) {
commentLines++;
} else {
normalLines++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -