现在的位置: 首页 > 综合 > 正文

java代码统计工具

2012年10月25日 ⁄ 综合 ⁄ 共 2573字 ⁄ 字号 评论关闭
 

当初初学java是为了统计自己的代码行数写的java代码行数统计工具,功能很简单,给出一个文件路径,统计出代码的总行数,注释行数,空行行数等等。

实现方面:遍历所有的java文件时用到了典型的递归:判断给是文件是目录还是文件,如果是目录,就遍历文件所有的子文件,对所有子文件递归调用该方法,如果是java文件,直接统计行数,统计行数用到了正则表达式。核心的代码如下:

遍历所有java文件:

 

public void getFileName(String filePath)

       {

              File f = new File(filePath);

              if(!f.isDirectory())//不是目录

              {

                     if(f.getName().endsWith(".java"))

                     {

                            count(f);

                     }

              }

              else//是目录

              {

                     String []fileList = f.list();

                     for(int i=0;i<fileList.length;i++)

                     {

                            File file = new File(filePath+"//"+fileList[i]);

                            if(!file.isDirectory())//不是目录

                            {

                                   if(file.getName().endsWith(".java"))

                                   {

                                          count(file);

                                   }

                            }

                            else         //是目录

                            {

                                   getFileName(file.getPath());//注意:不是getname()!

                            }

                     }

              }

             

       }

统计代码行数:

                     while((line = br.readLine())!=null)

                     {

                            line = line.trim();

                            if(line.matches("^[[//s]&&[^//n]]*$"))  // spaceLine   ?*$

                            {

                                   spaceLine++;

                            }

                            else if(line.startsWith("//")||(line.startsWith("/*")&&line.endsWith("*/")))

                            {

                                   commentLine++;

                            }

                            else if(line.startsWith("/*")&&!line.endsWith("*/"))

                            {

                                   commentLine++;

                                   comment = true;

                            }

                            else if((line.endsWith("*/"))&&comment==true)

                            {

                                   commentLine++;

                                   comment = false;

                            }

                            else if(comment==true)

                            {

                                   commentLine++;

                            }

                            else

                            {

                                   normalLine++;

                            }

                     }

完整的代码和可运行的jarhttp://download.csdn.net/user/china8848可以获得。

 

抱歉!评论已关闭.