`
fanyang219
  • 浏览: 8799 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

如何统计某目录下的java文件代码行数

    博客分类:
  • J2SE
阅读更多
(2008年4月25日23:43)
    最近在学java,写了一些代码,想统计自己到底写了多少代码,但统计起来比较烦琐,于是想写个程序方便以后统计。
    这个小程序能够统计某目录及其子目录下java文件代码行数,注释行数,空格行数以及各自所占百分比。
    源程序如下:
package linenum;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import javax.swing.*;

public class LineNum extends JFrame
{
	private JPanel topPanel = new JPanel();
	private JPanel bottomPanel = new JPanel();
	private JButton fileChoose = new JButton("选择目录");
	private JTextField fileField = new JTextField(20);
	private JFileChooser fc = new JFileChooser("选择目录");	
	private JTextArea filePathArea = new JTextArea(5 , 20);	
	//判断是否属于"/* */注释"
	private boolean isExplainStatus = false;
	
	//存储代码总行数值
	private int totalCount = 0;
	//存储注释总行数值
	private int explainCount = 0;
	//存储空行总行数值
	private int spaceCount = 0;
	//存储单个文件行数值
	private int count = 0;
	private InputStream input = null;
	private BufferedReader br = null;
	
	private String totalPath = "";
	private DecimalFormat myFormat = null;
	
	public LineNum(String title)
	{
	    super(title);	
	    //设置面板
        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        topPanel.setLayout(new GridLayout(1 , 2));
        bottomPanel.setLayout(new BorderLayout());
        topPanel.add(fileChoose);
        topPanel.add(fileField); 
        bottomPanel.add(new JScrollPane(filePathArea)); 
        filePathArea.setText("java文件:");
        container.add(topPanel , BorderLayout.NORTH);
        container.add(bottomPanel , BorderLayout.CENTER);  
        
        //添加选择目录监听,默认获取的是选择文件所在的父目录,程序统计对象是此父目录及其子目录下的所有java文件
        fileChoose.addActionListener(new ActionListener()
        {
			public void actionPerformed(ActionEvent e) 
			{				
				int result = fc.showOpenDialog(LineNum.this);
				if(result == JFileChooser.APPROVE_OPTION)
				{					
					String path = fc.getSelectedFile().getAbsolutePath();
					path = path.substring(0 , path.lastIndexOf("\\"));
                    fileField.setText(path); 
                    File file = new File(path);
                    CalculateLineNum(file);
				}
			}
        });
	}	

	/*
	 * 计算并显示统计信息
	 */
	private void CalculateLineNum(File file)
	{
		if(file.exists())
		{
			displayLineNum(file);
			myFormat = (DecimalFormat)NumberFormat.getPercentInstance();
			myFormat.applyPattern("0.00%");
			if(totalCount != 0)
			{
			    double programPercent = (double)(totalCount - explainCount - spaceCount)/(double)totalCount;
			    double explainPercent = (double)explainCount/(double)totalCount;
			    double spacePercent = (double)spaceCount/(double)totalCount;
			    filePathArea.setText(filePathArea.getText() + "\n" + " 总行数:" + totalCount + "行");
			    filePathArea.setText(filePathArea.getText() + "\n" + " 程序行数:" + (totalCount - explainCount - spaceCount) + "行,百分比:"+myFormat.format(programPercent));
			    filePathArea.setText(filePathArea.getText() + "\n" + " 注释行数:" + explainCount + "行,百分比:"+myFormat.format(explainPercent));
			    filePathArea.setText(filePathArea.getText() + "\n" + " 空行行数:" + spaceCount + "行,百分比:"+myFormat.format(spacePercent));
			}
			else
			{
				filePathArea.setText(filePathArea.getText() + "\n" + " 总行数:" + totalCount + "行");
			}
		}
	}
	
	//循环访问目录及子目录,统计代码总行数,注释行数及空行行数
	public void displayLineNum(File file)
	{
		totalPath+= "   ||   " + file.getName();
		String[] subPaths = file.list();
		if(subPaths.length == 0)
		{
			totalPath = totalPath.substring(0 , totalPath.lastIndexOf("   ||   "));
			return;
		}			
		//循环对子目录进行访问计算行数处理
		for(int i = 0 ; i < subPaths.length ; i++)
		{
			count = 0;
			File subFile = new File(file.getAbsolutePath() + "\\" + subPaths[i]);
			if(subFile.isFile())
			{
			    String subFilePath = subFile.getAbsolutePath();
			    String extendName = subFilePath.substring(subFilePath.lastIndexOf(".") + 1 , subFilePath.length());
			    if(!extendName.equals("java"))
			    {
				    continue;
			    }
			    try 
			    {
			        input = new FileInputStream(subFile);
			        BufferedReader br = new BufferedReader(new InputStreamReader(input));
			        String lineValue = br.readLine();
			        while(lineValue != null)
			        {
			            count++;
			            //对两种不同类型注释分别处理,对空行用空字符串来判断
			            if(isExplainStatus == false)
			            {
					        if(lineValue.trim().startsWith("//"))
					        {
					    	    explainCount++;
					        }
					        if(lineValue.trim().equals(""))
					        {
					    	    spaceCount++;
					        }
					        if(lineValue.trim().startsWith("/*"))
					        {
					        	explainCount++;
					    	    isExplainStatus = true;
					        }
			            }
			            else
			            {
			            	explainCount++;
					        if(lineValue.trim().startsWith("*/"))
					        {
					    	    isExplainStatus = false;
					        }
			            }
					    lineValue = br.readLine();
				    }
				    totalCount+= count;				        
				    String totalPath1 = totalPath + "   ||   " + subFile.getName();
				    
				    //显示单个文件的行数
				    filePathArea.setText(filePathArea.getText() + "\n" + totalPath1 + "   行数:" + count + "行--------totalCount:"+ totalCount);
				    br.close();
				    input.close();	
				} 
				catch (Exception e) 
				{				
				    e.printStackTrace();
				}
			}	
			else
			{					
				//循环调用displayLineNum函数,实现统计子目录行数数据
			    displayLineNum(subFile);
			}
		}
		totalPath = totalPath.substring(0 , totalPath.lastIndexOf("   ||   "));
	}
	
	public static void main(String args[])
	{
		LineNum lineFrame=new LineNum("java程序行数统计");
		lineFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		lineFrame.setBounds(212,159,600,420);
		lineFrame.setVisible(true);	
		lineFrame.setResizable(false);	
	}
}
分享到:
评论
31 楼 szhnet 2008-09-25  
xmx0632 写道
cosina 写道
robbin 写道
你这样也忒麻烦了,我一行shell命令就搞定了:

find . -type f -iname "*.java" -exec cat {} \; | wc -l 


像你那么兴师动众写一大陀Java代码真是画蛇添足。

BTW: wc *.java是不行滴,要加 -l 参数,还不能遍历子目录


  myeclipse 直接右键看的更快.....

右键后 在哪里看?


在这里,见附件。
30 楼 zhanglubing927 2008-09-13  
Eastsun 写道
程序是错的,随便写个统计就有问题:
/********
  A.java
********/

public class A{
}


引用

总行数:6行
程序行数:0行,百分比:0.00%
注释行数:6行,百分比:100.00%
空行行数:0行,百分比:0.00%


这个...
今天晚上我写了一个,好像也出了这个问题了...
29 楼 zhanglubing927 2008-09-13  
看完你的代码,受教了.
28 楼 fanyang219 2008-05-06  
re: wang8118
  你的程序考虑的比较全面,学习ing...
27 楼 wang8118 2008-05-06  

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CodeCounter
{

	static long normalLines = 0;

	static long commentLines = 0;

	static long blankLines = 0;

	public static void main(String[] args)
	{
		File f = new File("D:\\java");
		File[] codeFiles = f.listFiles();
		for (File child : codeFiles)
		{
			if (child.getName().matches(".*\\.java$"))
			{
				parse(child);
			}
		}

		System.out.println("正常代码:" + normalLines);
		System.out.println("注释代码:" + commentLines);
		System.out.println("空白行:" + blankLines);

	}

	private static void parse(File f)
	{
		BufferedReader br = null;
		boolean comment = false;
		try
		{
			br = new BufferedReader(new FileReader(f));
			String line = "";
			while ((line = br.readLine()) != null)
			{
				line = line.trim();
				if (line.matches("^[\\s&&[^\\n]]*$"))
				{
					blankLines++;
				} else if (line.startsWith("/*") && !line.endsWith("*/"))
				{
					commentLines++;
					comment = true;
				} else if (line.startsWith("/*") && line.endsWith("*/"))
				{
					commentLines++;
				} else if (true == comment)
				{
					commentLines++;
					if (line.endsWith("*/"))
					{
						comment = false;
					}
				} else if (line.startsWith("//"))
				{
					commentLines++;
				} else
				{
					normalLines++;
				}
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			if (br != null)
			{
				try
				{
					br.close();
					br = null;
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

}

26 楼 icelander 2008-05-06  
robbin 写道
你这样也忒麻烦了,我一行shell命令就搞定了:

find . -type f -iname "*.java" -exec cat {} \; | wc -l 


像你那么兴师动众写一大陀Java代码真是画蛇添足。

BTW: wc *.java是不行滴,要加 -l 参数,还不能遍历子目录


楼主写这个可以提高编程水平,又不是提高工作效率~
25 楼 syhan 2008-05-05  
显然是shell最快了
24 楼 geohox 2008-05-05  
用stepCounter插件就可以了  它会生成一个报表 很清晰明了
23 楼 fanyang219 2008-05-04  
re:anlibo
子目录多或者文件多的时候程序就会执行时间较长的。
22 楼 qn_0 2008-05-04  
Practiline Source Code Line Counter
21 楼 anlibo 2008-05-04  
我这儿运行你这个程序怎么这么慢的。。。。
20 楼 nickcen 2008-05-04  
robbin 写道
你这样也忒麻烦了,我一行shell命令就搞定了:

find . -type f -iname "*.java" -exec cat {} \; | wc -l 


像你那么兴师动众写一大陀Java代码真是画蛇添足。

BTW: wc *.java是不行滴,要加 -l 参数,还不能遍历子目录


lz都说是学习了,我觉得我们应该focus在他的代码有什么问题上。
如果lz的题目是怎么最快统计代码行数,你这个solution才是比较合理的reply。
19 楼 xmx0632 2008-05-04  
cosina 写道
robbin 写道
你这样也忒麻烦了,我一行shell命令就搞定了:

find . -type f -iname "*.java" -exec cat {} \; | wc -l 


像你那么兴师动众写一大陀Java代码真是画蛇添足。

BTW: wc *.java是不行滴,要加 -l 参数,还不能遍历子目录


  myeclipse 直接右键看的更快.....

右键后 在哪里看?
18 楼 1998a 2008-05-03  
用cobertura..连测试覆盖都有了..
很好很强大
17 楼 cddcdd 2008-05-03  
为了学习java,重复别人的东西,
不是没意义

就像别人会写helloworld
自己还是要重头写一遍一样

我们应该鼓励他
16 楼 javaxy 2008-05-03  
没事数这种东西有意义么?
15 楼 lijinyan3000 2008-05-03  
cuiyi.crazy 写道
统计目录下java文件代码行数不是很多opensource的东东么?
为什么要自己写?


别人的东西是别人的,如果以学习为目的的话,当然要自己写一遍才最好啊。
14 楼 cuiyi.crazy 2008-05-03  
统计目录下java文件代码行数不是很多opensource的东东么?
为什么要自己写?
13 楼 fanyang219 2008-05-02  
谢谢各位指点!!!
我对shell现在还不熟,正在学习。。。

现在在写五子棋的智能算法,不过现在我自己还能下得过,估计是棋点的评分标准有待改进,正在琢磨更加好的电脑算法。

现在我的电脑下棋思路是:
通过每个点四周的8个方向的棋的形势来评估此点的权值分数,扫描棋盘后得到最大权值分数的点,然后电脑在此点下棋。
12 楼 andyao 2008-05-01  
jarwang 写道
robbin 写道
你这样也忒麻烦了,我一行shell命令就搞定了:

find . -type f -iname "*.java" -exec cat {} \; | wc -l 


像你那么兴师动众写一大陀Java代码真是画蛇添足。

BTW: wc *.java是不行滴,要加 -l 参数,还不能遍历子目录



faint??java代码是多了点。但为统计一个总行数,就是安装一个xnux。难道就不是画蛇添足!!!!!



怎么说你呢?
robbin提了一个很好的解决办法,虚心学习就行了。
使用shell也不用装一个xnux,cgywin就可以。

ps:搞java的,shell之类的还是要熟悉熟悉好。

相关推荐

Global site tag (gtag.js) - Google Analytics