CountList2.java//用来统计java代码行数
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CountList2 {
int countSum;//代码行数
public int getFile(String filePath) throws FileNotFoundException {
try {
File file = new File(filePath);
if (file.isDirectory()) {//判断是否是文件夹
File[] codeFiles = file.listFiles();
int s = codeFiles.length;
for (int i = 0; i < s; i++) {
getFile(codeFiles[i].getPath());
}
} else {
if (file.getName().endsWith(".java")) {//判断是否是java文件
System.out.println(file.getName());//输出java文件名称
countSum += fileList(file);
}
}
} catch (FileNotFoundException e4) {
System.out.println("erroe1");
e4.printStackTrace();
} catch (@SuppressWarnings("hiding") IOException e1) {
System.out.println("erroe2");
e1.printStackTrace();
}
return countSum;
}
public int fileList(File file) {
int countSum = 0;//代码行数
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.matches("^[\\s&&[^\\n]]*$")) {
blankSum++;
} else if (line.startsWith("//")) {
commentSum++;
} else if (line.startsWith("/*")) {
commentSum++;
} else if (line.startsWith("*")) {
commentSum++;
} else if (line.endsWith("*/")) {
commentSum++;
} else {
countSum++;
}
}
br.close();
} catch (Exception e) {
System.out.println("erroe3");
e.printStackTrace();
}
return countSum;
}
}
countList1.java//用来测试
import java.io.FileNotFoundException;
public class countList1 {
public static void main(String[] args) throws FileNotFoundException {
String filePath = "E:\\nbtserver";
CountList2 fn = new CountList2();
int countSum1=fn.getFile(filePath);
System.out.println("countSum: " + countSum1);
}
}
<img src="https://img-blog.csdn.net/20150402112440991?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemVuZ3FpY2hlbmc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />