使用正则表达式统计代码行数

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class CodeCounter {
    static long normalLines=0;
    static long commentLines=0;
    static long whilteLinese=0;
    public static void main(String[] args) {
        File f=new File("c:\\Users\\Public\\Documents\\workspace\\eclipse-workspace\\TalkServer\\src\\talkServer\\");
        File[] codeFiles=f.listFiles();
        for(File child:codeFiles) {
            if(child.getName().matches(".*\\.java$")) {
                Parse(child);
            }
        
        }
        System.out.println("normalLines: "+normalLines);
        System.out.println("commentLines: "+commentLines);
        System.out.println("whilteLinese: "+whilteLinese);
        
    }
    private static void Parse(File child) {
        BufferedReader bf=null;
        boolean comment=false;
        try {
            bf=new BufferedReader(new FileReader(child));
            String line="";
            while((line=bf.readLine())!=null) {
                line=line.trim();
                if(line.matches("^[\\s&&[^\\n]]*$")) {
                    whilteLinese++;
                }else if(line.matches("/*")&&!line.endsWith("*/")) {
                    commentLines++;
                    comment =true;
                }else if(line.startsWith("/*")&&line.endsWith("*/")) {
                    commentLines++;
                }
                else if(true==comment) {
                    commentLines++;
                    if(line.endsWith("*/")) {
                        comment=false;
                    }
                }else if(line.startsWith("//")) {
                    commentLines++;
                    
                }else {
                    normalLines++;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}
 

猜你喜欢

转载自blog.csdn.net/u010731020/article/details/81222664
今日推荐