统计代码行数

public   class  ReadFile {
 
       /**
      *  @param  args
      *  @throws  IOException
      */
       public   static   void  main(String[] args)  throws  IOException {
           Long globalNum = 0L;  // 总行数
           List lineNums =  new  ArrayList();
           List exceptFileNames =  new  ArrayList();
           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 lineNums,
                List 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;
     }
 
}

你可能感兴趣的:(java)