import java.io.*; /** * @author aachen0 * @date 2018/4/16 17:20 * <p> * <p> * IDE:IntelliJ IDEA */ public class AnalyseCode { public static void main(String[] args) throws IOException { FileReader fileReader = new FileReader(new File("D:\\aachen0\\IDEA_WorkSpace\\JavaBasic\\src\\AnalyseCode.java"));// 里边的文件路径为要统计的代码文件的路径 BufferedReader bufferedReader = new BufferedReader(fileReader); String line = null; String regexBlankLine = "\\s*"; // 空行的正则 int countBlankLine = 0; String regexAnnotation = "\\s*/{2}.*"; // 单行注释的正则 String regexAnnotationStart = "\\s*/\\x2A.*";// 多行注释开始标记 String regexAnnotationEnd = "\\s*\\x2A/.*";// 多行注释结束 int countAnnotation = 0; int countOther = 0; while (null != (line = bufferedReader.readLine())) { // 多行注释统计 if (line.matches(regexAnnotationStart)) { do { countAnnotation++; line = bufferedReader.readLine(); } while (!line.matches(regexAnnotationEnd)); } // 空行统计 if (line.matches(regexBlankLine)) { countBlankLine++; } else if (line.matches(regexAnnotation)) {// 单行注释统计 countAnnotation++; } else countOther++; } bufferedReader.close(); System.out.println("总行数:" + (countAnnotation + countBlankLine + countOther)); System.out.println("空行:" + countBlankLine); System.out.println("注释行:" + countAnnotation); System.out.println("代码行:" + countOther); } }