`
JaHunter
  • 浏览: 89537 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

统计代码行数

    博客分类:
  • java
 
阅读更多
public class ReadFile {
 
      /**
      * @param args
      * @throws IOException
      */
      public static void main(String[] args) throws IOException {
           Long globalNum = 0L; // 总行数
           List<Long> lineNums = new ArrayList<Long>();
           List<String> exceptFileNames = new ArrayList<String>();
           exceptFileNames.add( "project2" );//不统计目录
           exceptFileNames.add( "test");//不统计目录
          String path = "D:\\source\\project" ;//项目目录
           File file = new File(path);
            traversalFile(file, lineNums, exceptFileNames);
            for (Long num : lineNums) {
                globalNum = globalNum + num;
           }
           System. out.println(globalNum); // 310375
     }
 
      /**
      * 得到目录的叶子java文件,并统计文件里有多少行,将行数放到list中
      *
      * @param file
      * @throws IOException
      */
      public static void traversalFile(File file, List<Long> lineNums,
                List<String> exceptFileNames) throws IOException {
           File[] childList = file.listFiles();
           String fileName = null;
           String extra = null;
            for (File child : childList) {
                fileName = child.getName();
                 if (child.isDirectory()) {
                      if (exceptFileNames != null
                                && !exceptFileNames.contains(child.getName())) {
                            traversalFile(child, lineNums, exceptFileNames);
                     }
                } else {
                     extra = fileName.contains( ".") ? fileName.substring(fileName
                                .lastIndexOf( ".")) : fileName;
                      if (extra.equals( ".java") || extra.equals(".jsp" )
                                || extra.equals( ".js")) {
                          System. out.println(child.getName().substring(
                                     child.getName().lastIndexOf( ".")));
                           lineNums.add( getLineNum(child));
                     }
                }
           }
     }
 
      /**
      * 得到某个文件有多少行(非目录)
      *
      * @param file
      * @return
      * @throws IOException
      */
      public static long getLineNum(File file) throws IOException {
            long num = 0L;
           FileInputStream f = new FileInputStream(file);
           BufferedReader dr = new BufferedReader( new InputStreamReader(f));
           String line = dr.readLine();
            while (line != null) {
                 if (!line.trim().equals( "")) {
                     num++;
                }
                line = dr.readLine();
           }
            return num;
     }
 
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics