栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java工具类之实现java获取文件行数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java工具类之实现java获取文件行数

工具类代码,取得当前项目中所有java文件总行数,代码行数,注释行数,空白行数

复制代码 代码如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class JavaCode {
 private static final String PROJECT_DIR = "C:\test";
 private static int totle = 0;  //总行数    
 private static int source  = 0;  //代码行数   
 private static int blank  = 0;  //空白行数    
 private static int comments = 0; //注释行数

 
 private static void listNext(File dir) {
  File[] files = dir.listFiles();
  for (int i = 0; i < files.length; i++) {
   //判断是否是文件夹,如果是文件夹继续向下检索
   if (files[i].isDirectory()) {
    listNext(files[i]);
   } else {
    try {
     if (files[i].getName().endsWith(".java")) {
      System.out.println(files[i].getAbsolutePath());
      javaLine(files[i]);
     }
    }catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }

 
 private static void javaLine(File f) throws FileNotFoundException, IOException{
  String strLine = "";
  String str = fromFile(f);
  if (str.length() > 0) {
   while (str.indexOf('n') != -1) {
    totle++;
    //System.out.println(totle);
    strLine = str.substring(0, str.indexOf('n')).trim();
    //str = str.substring(str.indexOf('n') + 1, str.length());
    if (strLine.length() == 0 ) {
     blank++;
    }else if (strLine.charAt(0) == '*' || strLine.charAt(0) == '/') {
     comments++;
    }else{
     source++;
     String regEx = "^*//";
     if(regEx(strLine,regEx)){
      comments++;
     }
    }
    str = str.substring(str.indexOf('n') + 1, str.length());
   }
  } 
 }

 
 private static String  fromFile(File f) throws FileNotFoundException,IOException {
  FileInputStream fis = new FileInputStream(f);
  byte[] b = new byte[(int) f.length()];
  fis.read(b);
  fis.close();
  return new String(b);
 }

 
 private static boolean regEx(String str,String regEx){
  Pattern p=Pattern.compile(regEx);
  Matcher m=p.matcher(str);
  boolean result=m.find();
  return result;
 }
 public static void main(String[] args) throws FileNotFoundException, IOException {
  //File root = new File(PROJECT_DIR);
  File directory = new File("");//参数为空
  //获取项目路径
  String projectFile = directory.getCanonicalPath() ;
  System.out.println(projectFile+"===============");
  listNext(new File(projectFile));
  System.out.println(totle+1);
  System.out.println(source);
  System.out.println(blank);
  System.out.println(comments);
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152281.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号