某大厂二面笔试题,java原生代码方式实现统计java代码行数、注释行数、package行数、import行数和空行数。遂稍写了一下,如有更优,欢迎指正
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CodeCounter {
static int codeLineCount;//代码行
static int codeBlackCount;//空白行
static int codeCommentCount;//注释行数
static int packageLineCount;//package行数
static int importLineCount;//import行数
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\FUBINGBING\\Desktop\\code");
showAllFileLines(file);
System.out.println("代码行数:"+ codeLineCount);
System.out.println("空白行:"+ codeBlackCount);
System.out.println("注释行数:"+ codeCommentCount);
System.out.println("package行数:"+ packageLineCount);
System.out.println("import行数:"+ importLineCount);
System.out.println("总行数:"+ (codeLineCount + codeBlackCount + codeCommentCount + packageLineCount + importLineCount));
}
static void showAllFileLines(File dir) throws IOException {
BufferedReader br = null;
String s = null;
File[] fs = dir.listFiles();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getAbsolutePath().endsWith(".java")) {
br = new BufferedReader(new FileReader(fs[i]));
boolean comm = false;
while((s = br.readLine()) != null) {
if(s.startsWith("/*") && s.endsWith("*/")) {
codeCommentCount++;
}else if(s.trim().startsWith("//")) {
codeCommentCount++;
}else if(s.trim().startsWith("/*") && !s.endsWith("*/")) {
codeCommentCount++;
comm = true;
}else if(!s.startsWith("/*") && s.endsWith("*/")) {
codeCommentCount++;
comm = false;
}else if(comm) {
codeCommentCount++;
}else if(s.trim().length() < 1) {
codeBlackCount++;
}else if(s.split(" ")[0].equals("package")) {
packageLineCount++;
}else if(s.split(" ")[0].equals("import")) {
importLineCount++;
}else {
codeLineCount++;
}
}
}
if(fs[i].isDirectory()) {
showAllFileLines(fs[i]);
}
}
}
}
学无止境,每天进步一点点 ~