package com;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CodeCounter {
static long codeLines = 0;
static long commentLines = 0;
static long spaceLines = 0;
static long classnum = 0;
static long num = 0;
public static void main(String[] args) {
File f = new File("F:\\JAVA\\javacode\\GBN.java"); //这里的目录要输入你要统计代码的文件夹目录
if(f.exists()) {
judge(f);
}
System.out.println("实际代码行数为:"+codeLines);
System.out.println("注释代码行数为:"+commentLines);
System.out.println("空行行数为:"+spaceLines);
num = codeLines+commentLines+spaceLines;
System.out.println("总的行数为:"+num);
System.out.println("类的数目为:"+classnum);
}
private static void judge(File f) {
if(!f.isFile()) {
File[] fs = f.listFiles();//返回的是一个文件数组 是这个文件下面所有的子文件的pathroad
for(File child: fs) { //这是遍历的意思 c++里面也可以这样写
judge(child);
}
}
if(f.exists()&&f.isFile()) {//this abstract pathname is a normal file
counter(f);
}
}
private static void counter(File child) {
FileReader fr; // read file
try {
fr = new FileReader(child);
BufferedReader br = new BufferedReader(fr);//把文件里面的内容缓存到br里面
String line = "";
boolean flag = false;
if(child.getName().matches(".*cpp$")||child.getName().matches(".*java$")||
child.getName().matches(".*txt$")) { //任意选择文件格式
try {
while((line=br.readLine())!=null) {
String l = line.trim();//去除前导空字符
if(l.matches(".*class.+")) {//匹配前后均有0~n个字符的含有class字样的行
classnum++;
}
if(l.matches("^[[\\s]&&[^\\n]]*")) {//保证是空行
spaceLines++;
}
else if(l.startsWith("/*")&&l.endsWith("*/")) {
commentLines++;
flag = false;
}
else if(l.startsWith("/*")) {
commentLines++;
flag = true;
}
else if(l.endsWith("*/")) {
commentLines++;
flag = false;
}
else if(true == flag) {
commentLines++;
}
else if(l.startsWith("//")) {
commentLines++;
}
else {
codeLines++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
统计文件的代码
最新推荐文章于 2023-05-24 21:35:53 发布