使用正则表达式进行单词统计

本文介绍了一个用于统计Java项目中正常代码行数、注释行数及空白行数的Java工具。该工具通过遍历指定目录下的所有.java文件,并解析每一行内容来实现统计功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 import java.io.BufferedReader;
 2 import java.io.File;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 
 7 public class CodeCounter {
 8     
 9     static long normalLines = 0;
10     static long commentLines = 0;
11     static long whiteLines = 0;
12     
13     public static void main(String[] args) {
14         File f = new File("D:\\share\\JavaProjects\\TankWar1.9.11\\src");
15         File[] codeFiles = f.listFiles();
16         for(File child : codeFiles){
17             if(child.getName().matches(".*\\.java$")) {
18                 parse(child);
19             }
20         }
21         
22         System.out.println("normalLines:" + normalLines);
23         System.out.println("commentLines:" + commentLines);
24         System.out.println("whiteLines:" + whiteLines);
25         
26     }
27 
28     private static void parse(File f) {
29         BufferedReader br = null;
30         boolean comment = false;
31         try {
32             br = new BufferedReader(new FileReader(f));
33             String line = "";
34             while((line = br.readLine()) != null) {
35                 line = line.trim();
36                 if(line.matches("^[\\s&&[^\\n]]*$")) {
37                     whiteLines ++;
38                 } else if (line.startsWith("/*") && !line.endsWith("*/")) {
39                     commentLines ++;
40                     comment = true;    
41                 } else if (line.startsWith("/*") && line.endsWith("*/")) {
42                     commentLines ++;
43                 } else if (true == comment) {
44                     commentLines ++;
45                     if(line.endsWith("*/")) {
46                         comment = false;
47                     }
48                 } else if (line.startsWith("//")) {
49                     commentLines ++;
50                 } else {
51                     normalLines ++;
52                 }
53             }
54         } catch (FileNotFoundException e) {
55             e.printStackTrace();
56         } catch (IOException e) {
57             e.printStackTrace();
58         } finally {
59             if(br != null) {
60                 try {
61                     br.close();
62                     br = null;
63                 } catch (IOException e) {
64                     e.printStackTrace();
65                 }
66             }
67         }
68     }
69 
70 }

 

转载于:https://www.cnblogs.com/XiDaPuBen/p/8678754.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值