import java.io.*;
public class Codecounter {
public static int normalLines = 0;//有效程序行数
public static int whiteLines = 0;//空白行数
public static int commentLines = 0;//注释行数
public static void main(String [] args){
File f = new File("e:\\JAVA编译");//创建File对象f,指定路径为E:\JAVA编译
File[] codeFile = f.listFiles();// 取得JAVA编译文件夹下的文件作为对象
for(File file:codeFile){ //读取每一个File对象
if(file.getName().matches(".*\\.java")){ //提取后缀名为.java的文件
parse(file);
}
}
System.out.println("代码行数 " + normalLines);
System.out.println("空行数 " + whiteLines);
System.out.println("注释行数 " + commentLines);
System.out.println("总行数"+(normalLines+whiteLines+commentLines));
} //显示到屏幕
public static void parse(File file){ //声明一个参数为File对象file的,公有的,静态的,名为parse的方法
BufferedReader br = null; //定义一个BufferedReader类对象br
boolean comment = false; //定义一个boolean型变量 comment,并初始化
//判断此行是否为注释行
try {
br = new BufferedReader(new FileReader(file));
String line = ""; //创建一个字符串对象line
while((line = br.readLine()) != null){
line = line.trim();
if(line.matches("^[\\s&&[^\\n]]*$")){ //正则表达式...【全行0或多个空格】
whiteLines ++;
}else if(line.startsWith("/*")&& ! line.endsWith("*/")){ <span style="font-family: Arial, Helvetica, sans-serif;">//判断此行为"/*"开头的注释行</span>
commentLines ++ ;
comment = true;
}else if(comment == true && !line.endsWith("*/")){ <span style="font-family: Arial, Helvetica, sans-serif;">//为多行注释中的一行(不是开头和结尾)</span>
commentLines ++ ;
}else if(comment == true && line.endsWith("*/")){ <span style="font-family: Arial, Helvetica, sans-serif;">//为多行注释的结束行</span>
commentLines ++ ;
comment = false;
}else if(line.startsWith("//")){ <span style="font-family: Arial, Helvetica, sans-serif;">//单行注释行</span>
commentLines ++ ;
}else{
normalLines ++; <span style="font-family: Arial, Helvetica, sans-serif;">//正常代码行</span>
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
改编的一份JAVA代码行数统计的代码
最新推荐文章于 2020-02-07 18:10:39 发布