统计有效代码
import java.io.*;
public class countUsefulLines {
static long normalLines = 0; //文件总共行数
static long commentLines = 0; //注释行
static long whiteLines = 0; //空格行
public static void main(String[] args) {
File f = new File("C:/Users/UserName/Desktop/ed.txt");
if(!f.exists()) {
p("不存在该文件");
System.exit(-1);
}
BufferedReader br = null;
boolean comment;
try {
br = new BufferedReader(new FileReader(f));
String line;
comment = false;
while((line = br.readLine()) != null) {
normalLines ++; //只要非空就行数加1
if(line.matches("^\\s*$"))
whiteLines ++; //匹配空行加1
else if(true == comment) {
commentLines ++; //只要还在注释行则加1
if(line.endsWith("*/"))
comment = false; //退出注释行置为false
}
else if(line.startsWith("//"))
commentLines ++; //注释行
else if(line.startsWith("/*")) {
commentLines ++;
if(!line.endsWith("*/"))
comment = true; //开始进入注释块
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
p("总共有" + normalLines + "行代码");
p("总共有" + whiteLines + "行空行代码");
p("总共有" + commentLines + "行注释行代码");
p("有效代码行数:" + (normalLines-whiteLines-commentLines));
}
}
static void p(Object o) {
System.out.println(o);
}
}