沙漠中的孤狼 发表于 2013-1-26 15:55:59

源代码行数统计器

前几天需要知道某个文件(c,cpp,java)的行数,自己做了一个统计源代码行数的一个小小的软件,想跟大家分享。

Java源代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

public class CodeLineCounter extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;

//顶部,底部容器
private JPanel topPanel,bottomPanel, panel;
//欢迎,目录标签
private JLabel welcomeLabel, catalogLabel;
private DefaultListModel listModel;
//统计处于列表
private JList statusArea;
//目录文本框
private JTextField catalogField;
//打开文件,统计,重置,退出等按钮
private JButton explorBtn, statusBtn, resetBtn, exitBtn;
//文件选择器
private JFileChooser chooser = new JFileChooser();

//统计标记
private boolean isAlreadyStat = false;


// 判断是否属于"/* */注释"   
    private boolean isExplainStatus = false;   
   
    //行数数列
    private int[] count;
    //存储代码总行数值
    private int totalCount = 0;
    //存储单个文件行数值   
    private int codeCount = 0;
    //存储注释总行数值
    private int explainCount = 0;
    //存储空行总行数值
    private int spaceCount = 0;
   
    private InputStream input = null;
    private BufferedReader br = null;

public CodeLineCounter(String title) {
super(title);
//设置大小和显示位置
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds((screenSize.width - 505)/2, (screenSize.height - 379)/2, 505, 379);
//设置布局
this.setLayout(new BorderLayout());

//创建顶层容器
topPanel = new JPanel();
this.add(topPanel, BorderLayout.NORTH);

//创建欢迎标签
welcomeLabel = new JLabel();
welcomeLabel.setForeground(Color.RED);
String space = "                     " + "                     ";
welcomeLabel.setText("   欢迎您使用Java版源代码行数计数器!" + space);
topPanel.add(welcomeLabel);

//创建统计区域列表
listModel = new DefaultListModel();
for(int i = 0;i < 15;i++)
listModel.addElement(" ");
statusArea = new JList(listModel);
statusArea.setSelectionBackground(Color.WHITE);
statusArea.setSelectionForeground(Color.BLACK);
this.add(statusArea, BorderLayout.CENTER);

//创建底部容器
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(3, 1));
this.add(bottomPanel, BorderLayout.SOUTH);

panel = new JPanel();
bottomPanel.add(panel);
//创建目录标签
catalogLabel = new JLabel("源代码路径:");
panel.add(catalogLabel);
//创建目录文本框
catalogField = new JTextField(50);
panel.add(catalogField);
//打开文件按钮
explorBtn = new JButton("打开文件...");
explorBtn.addActionListener(new ButtonActionListener());
panel.add(explorBtn);

panel = new JPanel();
bottomPanel.add(panel);
panel.add(new JLabel("※※※※※★★★★★☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆★★★★★※※※※※"));

panel = new JPanel();
bottomPanel.add(panel);
//创建统计按钮
statusBtn = new JButton("统计");
statusBtn.addActionListener(new ButtonActionListener());
panel.add(statusBtn);
//占位标签
panel.add(new JLabel("             "));
//创建重置按钮
resetBtn = new JButton("重置");
resetBtn.addActionListener(new ButtonActionListener());
panel.add(resetBtn);
//占位标签
panel.add(new JLabel("             "));
//创建退出按钮
exitBtn = new JButton("退出");
exitBtn.addActionListener(new ButtonActionListener());
panel.add(exitBtn);
}

/**
* 注册按钮监听事件
*/
class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == explorBtn) {
      chooser.setDialogTitle("打开");
      CodeLineCounter.fileFilter(chooser);
      chooser.showOpenDialog(null);
      File file = chooser.getSelectedFile();
      if(file != null) {
      isAlreadyStat = false;
      String type = chooser.getName(file).substring(chooser.getName(file).indexOf(".") + 1).toLowerCase();
      //System.out.println(type);
      if(type != null && (type.equals("java") || type.equals("c") || type.equals("cpp"))) {
      catalogField.setText(file.getAbsolutePath());
      } else {
      String[] msg = {"类型错误!!!!!!", "统计类型为‘java’,‘c’,‘cpp’。"};
      JOptionPane.showMessageDialog(null, msg, "友情提示", JOptionPane.INFORMATION_MESSAGE);
      }
      }
} else if(e.getSource() == statusBtn) {
if(!isAlreadyStat) {
File file = chooser.getSelectedFile();
if(file != null) {
String name = chooser.getName(file);
      String type = name.substring(name.indexOf(".") + 1).toLowerCase();
      System.out.println(type);
      System.out.println(statusArea.getSize().width);
      int[] countArray = getLineCount(chooser);
      listModel.add(1, "正在获取文件类型...");
      listModel.add(2, "统计文件类型:" + type + "文件");
      listModel.add(4, "正在获取文件名称...");
      listModel.add(5, "统计文件名称:" + name);
      listModel.add(8, "正在统计源代码行数...");
      listModel.add(9, "程序行数:※※※※※ <" + countArray + "行> ※※※※※");
      listModel.add(10, "注释行数:※※※※※ <" + countArray + "行> ※※※※※");
      listModel.add(11, "空行行数:※※※※※ <" + countArray + "行> ※※※※※");
      listModel.add(13, "总 行 数:<" + countArray + "行>");
      
      isAlreadyStat = true;
} else {
JOptionPane.showMessageDialog(null, "   请选择要统计的源代码。", "友情提示", JOptionPane.INFORMATION_MESSAGE);
}
}
} else if(e.getSource() == resetBtn) {
for(int i = 0;i < 15;i++)
listModel.add(i, " ");
catalogField.setText("");
//isAlreadyStat = false;
} else if(e.getSource() == exitBtn) {
System.exit(0);
}
}
}

/**
* 过滤器
*/
private static void fileFilter(JFileChooser chooser) {
    chooser.setAcceptAllFileFilterUsed(false);
   
    chooser.setFileFilter(new FileFilter() {
    public boolean accept(File f) {
    return ((f.getName().endsWith(".java")) || (f.isDirectory()));
    }

    public String getDescription() {
    return "Java源程序(*.java)";
    }
    });
    chooser.setFileFilter(new FileFilter() {
    public boolean accept(File f) {
    return ((f.getName().endsWith(".c")) || (f.isDirectory()));
    }

    public String getDescription() {
    return "C源程序(*.c)";
    }
    });
    chooser.setFileFilter(new FileFilter() {
    public boolean accept(File f) {
    return ((f.getName().endsWith(".cpp")) || (f.isDirectory()));
    }

    public String getDescription() {
    return "C++源程序(*.cpp)";
    }
    });
    chooser.addChoosableFileFilter(new FileFilter() {
    public boolean accept(File f) {
    return true;
    }

    public String getDescription() {
    return "所有文件(*.*)";
    }
    });
}

    /**
   * @param chooser
   * 获取行数
   */   
    public int[] getLineCount(JFileChooser chooser) {
      count = new int;
      try {
      input = new FileInputStream(chooser.getSelectedFile());
      br = new BufferedReader(new InputStreamReader(input));
      String lineValue = br.readLine();   
      while(lineValue != null) {
      codeCount++;
      //对两种不同类型注释分别处理,对空行用空字符串来判断
      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 = codeCount + explainCount + spaceCount;
      
      count= totalCount;
      count= codeCount;
      count= explainCount;
      count= spaceCount;
            
      br.close();
      input.close();
      } catch (Exception e) {
      e.printStackTrace();
      }
      return count;
    }

/**
* @param args
*/
public static void main(String[] args) {
//设置感官
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}

CodeLineCounter counter = new CodeLineCounter("源代码行数计数器 v1.0");
counter.pack();
counter.setResizable(false);
counter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
counter.setVisible(true);
}
}
页: [1]
查看完整版本: 源代码行数统计器