User Tools

Site Tools


java-example:total-line-number

统计代码行数

package com.platform;
 
/**
 * 用来统计某个文件夹下到底有多少行代码的
 * @author Morgan.L
 * @version 1.0
 * @date 2020/10/26 16:31
 */
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
 
public class MainTotalLineNumber {
 
  public static void main(String[] args) throws IOException {
    countLine("C:/git5/First", true);
    System.out.println("totalLineNum=>" + totalLineNum + " totalFileNum=>" + totalFileNum
      + " lineNum/fileNum=>" + (totalLineNum/totalFileNum));
 
    totalLineNum = 0;
    totalFileNum = 0;
    countLine("C:/git5/Second", true);
    System.out.println("totalLineNum=>" + totalLineNum + " totalFileNum=>" + totalFileNum
      + " lineNum/fileNum=>" + (totalLineNum/totalFileNum));
  }
 
  private static BufferedReader bufferedReader = null;
  private static int totalLineNum = 0;
  private static int totalFileNum = 0;
  private static String[] allowFileTypes = {".java", ".xml", ".properties"};
 
  private static void countLine(String filePath, boolean ignoreBlankLine) throws IOException {
    File file = new File(filePath);
    countOneFile(file, ignoreBlankLine);
  }
 
  private static void countOneFile(File file, boolean ignoreBlankLine) throws IOException {
    File[] children = file.listFiles();
    if(children == null) return;
 
    for (int i = 0; i < children.length; i++) {
      if(children[i].isDirectory() && "target".equals(children[i].getName())) {
        continue;
      }
 
      if (children[i].isFile() && validFileType(children[i].getName(), allowFileTypes)) {
        totalFileNum++;
 
        bufferedReader = new BufferedReader(new FileReader(children[i]));
        if (ignoreBlankLine) {
          String line;
          while ((line = bufferedReader.readLine()) != null) {
            if (StringUtils.isNotBlank(line)) {
              totalLineNum++;
            }
          }
        } else {
          while (bufferedReader.readLine() != null) {
            totalLineNum++;
          }
        }
      } else {
        countOneFile(children[i], ignoreBlankLine);
      }
    }
  }
 
  public static boolean validFileType(String filePath, String... allowTypes) {
    if (StringUtils.isNotBlank(filePath)) {
      for (String type : allowTypes) {
        if (filePath.indexOf(type) > -1) {
          return true;
        }
      }
    }
    return false;
  }
}
java-example/total-line-number.txt · Last modified: 2021/11/15 07:53 by morgan0329

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki