1 package com.syl.demo.test;
2
3 import java.io.*;
4
5 /**
6 * java代码行数统计工具类
7 * Created by 孙义朗 on 2017/11/17 0017.
8 */
9 public class CountCodeLineUtil {
10 private static int normalLines = 0; //有效程序行数
11 private static int whiteLines = 0; //空白行数
12 private static int commentLines = 0; //注释行数
13
14 public static void countCodeLine(File file) {
15 System.out.println("代码行数统计:" + file.getAbsolutePath());
16 if (file.exists()) {
17 try {
18 scanFile(file);
19 } catch (IOException e) {
20 e.printStackTrace();
21 }
22 } else {
23 System.out.println("文件不存在!");
24 System.exit(0);
25 }
26 System.out.println(file.getAbsolutePath() + " ,java文件统计:" +
27 "总有效代码行数: " + normalLines +
28 " ,总空白行数:" + whiteLines +
29 " ,总注释行数:" + commentLines +
30 " ,总行数:" + (normalLines + whiteLines + commentLines));
31 }
32
33 private static void scanFile(File file) throws IOException {
34 if (file.isDirectory()) {
35 File[] files = file.listFiles();
36 for (int i = 0; i < files.length; i++) {
37 scanFile(files[i]);
38 }
39 }
40 if (file.isFile()) {
41 if (file.getName().endsWith(".java")) {
42 count(file);
43 }
44 }
45 }
46
47 private static void count(File file) {
48 BufferedReader br = null;
49 // 判断此行是否为注释行
50 boolean comment = false;
51 int temp_whiteLines = 0;
52 int temp_commentLines = 0;
53 int temp_normalLines = 0;
54
55 try {
56 br = new BufferedReader(new FileReader(file));
57 String line = "";
58 while ((line = br.readLine()) != null) {
59 line = line.trim();
60 if (line.matches("^[//s&&[^//n]]*$")) {
61 // 空行
62 whiteLines++;
63 temp_whiteLines++;
64 } else if (line.startsWith("/*") && !line.endsWith("*/")) {
65 // 判断此行为"/*"开头的注释行
66 commentLines++;
67 comment = true;
68 } else if (comment == true && !line.endsWith("*/")) {
69 // 为多行注释中的一行(不是开头和结尾)
70 commentLines++;
71 temp_commentLines++;
72 } else if (comment == true && line.endsWith("*/")) {
73 // 为多行注释的结束行
74 commentLines++;
75 temp_commentLines++;
76 comment = false;
77 } else if (line.startsWith("//")) {
78 // 单行注释行
79 commentLines++;
80 temp_commentLines++;
81 } else {
82 // 正常代码行
83 normalLines++;
84 temp_normalLines++;
85 }
86 }
87
88 System.out.println(file.getName() +
89 " ,有效行数" + temp_normalLines +
90 " ,空白行数" + temp_whiteLines +
91 " ,注释行数" + temp_commentLines +
92 " ,总行数" + (temp_normalLines + temp_whiteLines + temp_commentLines));
93 } catch (FileNotFoundException e) {
94 e.printStackTrace();
95 } catch (IOException e) {
96 e.printStackTrace();
97 } finally {
98 if (br != null) {
99 try {
100 br.close();
101 br = null;
102 } catch (IOException e) {
103 e.printStackTrace();
104 }
105 }
106 }
107 }
108
109 //测试
110 public static void main(String[] args) {
111 File file = new File("F:\\myweb");
112 countCodeLine(file);
113 }
114 }