统计.java文件的有效代码行

规则:以";","{","}"结束的行为有效行;
1.接收一个文件或目录;
2.读单个文件或目录下的多个文件;
3.排除package行;
4.排除import行;
5.排除空白行;
6.排除单行注释;
7.排除文档注释;
8.去掉无效";";
9.去掉块注释;

源码如下:

package com.zzxsl.io;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Grover on 05/06/2016.
 */
public final class Statistics {
    /**
     * 数量
     */
    private int count;

    public Statistics(String filePath) {
        File file = new File(filePath);
        if (!file.exists()){ //判断是否存在
            return;
        }

        if (file.isFile()){ //判断是否为文件
            readFile(file);
            return;
        }
        //目录
        findFile(file);

    }

    /**
     * 在目录中找.java文件
     * @param dir
     */
    private void findFile(File dir) {
        for (File file : dir.listFiles()) {
            if(file.isDirectory()){
                findFile(file);
                continue;
            }
            readFile(file);
        }

    }

    /**
     * 读文件
     * @param file
     */
    private void readFile(File file) {
        if(!file.getName().endsWith(".java")){
            return;
        }
        try {
            BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line;
            StringBuilder content = new StringBuilder();
            while ((line = fileReader.readLine()) != null){
                line = exclusionInvalidSemicolon(line.trim());
                if(line.startsWith("package")
                        || line.startsWith("import")
                        || line.equals("") //空行
                        || line.startsWith("//")){ //单行注释
                    continue;
                }
                content.append(line);
            }
            exclusionCommentAndCalculate(content.toString());
        } catch (UnsupportedEncodingException e) {
            System.err.println("不支持用指定编码解析!");
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            System.err.println("文件路径不存在!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 去掉文档注释和块注释,并计算";"数量
     * @param content
     * @return
     */
    private void exclusionCommentAndCalculate(String content) {
        calculateSemicolonCount(content.replaceAll("/\\*.*?\\*/",""));
    }

    /**
     * 计算";"数量;
     * @param text
     */
    private void calculateSemicolonCount(String text) {
        Matcher matcher = Pattern.compile("[;\\{\\}]").matcher(text);
        while (matcher.find()){
            count += 1;
        }
    }

    /**
     * 去掉无效的分号
     * @param text
     * @return
     */
    private String exclusionInvalidSemicolon(String text) {
        return text.replaceAll("^;*","").replaceAll(";.*//.*",";");
    }

    public int getCount() {
        return count;
    }
}

猜你喜欢

转载自zhuzaixiaoshulin.iteye.com/blog/2303436