统计文件的代码

来源:互联网 发布:php 图片水印 编辑:程序博客网 时间:2024/05/18 03:01
package com;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 codeLines = 0;static long commentLines = 0;static long spaceLines = 0;static long classnum = 0;static long num = 0;public static void main(String[] args) {File f = new File("F:\\JAVA\\javacode\\GBN.java");//这里的目录要输入你要统计代码的文件夹目录if(f.exists()) {judge(f);}System.out.println("实际代码行数为:"+codeLines);System.out.println("注释代码行数为:"+commentLines);System.out.println("空行行数为:"+spaceLines);num = codeLines+commentLines+spaceLines;System.out.println("总的行数为:"+num);System.out.println("类的数目为:"+classnum);}private static void judge(File f) {if(!f.isFile()) {File[] fs = f.listFiles();//返回的是一个文件数组   是这个文件下面所有的子文件的pathroadfor(File child: fs) {     //这是遍历的意思 c++里面也可以这样写judge(child);}}if(f.exists()&&f.isFile()) {//this abstract pathname is a normal filecounter(f);}}private static void counter(File child) {FileReader fr;  // read filetry {fr = new FileReader(child);BufferedReader br = new BufferedReader(fr);//把文件里面的内容缓存到br里面String line = "";boolean flag = false;if(child.getName().matches(".*cpp$")||child.getName().matches(".*java$")||child.getName().matches(".*txt$")) {   //任意选择文件格式try {while((line=br.readLine())!=null) {String l = line.trim();//去除前导空字符if(l.matches(".*class.+")) {//匹配前后均有0~n个字符的含有class字样的行classnum++;}if(l.matches("^[[\\s]&&[^\\n]]*")) {//保证是空行 spaceLines++;}else if(l.startsWith("/*")&&l.endsWith("*/")) {commentLines++;flag = false;}else if(l.startsWith("/*")) {commentLines++;flag = true;}else if(l.endsWith("*/")) {commentLines++;flag = false;}else if(true == flag) {commentLines++;}else if(l.startsWith("//")) {commentLines++;}else {codeLines++;}}} catch (IOException e) {e.printStackTrace();}}} catch (FileNotFoundException e) {e.printStackTrace();}}}

0 0
原创粉丝点击