统计代码有效行数

来源:互联网 发布:警服照试穿软件 编辑:程序博客网 时间:2024/06/05 17:15

统计有效代码

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 ++; //只要非空就行数加1if(line.matches("^\\s*$"))whiteLines ++; //匹配空行加1else if(true == comment) {commentLines ++; //只要还在注释行则加1if(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);}}


原创粉丝点击