java工具类之实现java获取文件行数
工具类代码,取得当前项目中所有java文件总行数,代码行数,注释行数,空白行数
import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.filereader;
import java.io.ioexception;
import java.io.reader;
import java.util.regex.matcher;
import java.util.regex.pattern;
/**
*
* @author administrator
*
*/
public class javacode {
private static final string project_dir = "c:\\test";
private static int totle = 0; //总行数
private static int source = 0; //代码行数
private static int blank = 0; //空白行数
private static int comments = 0; //注释行数
/**
* 读取文件夹内java文件
* @param dir
*/
private static void listnext(file dir) {
file[] files = dir.listfiles();
for (int i = 0; i < files.length; i++) {
//判断是否是文件夹,如果是文件夹继续向下检索
if (files[i].isdirectory()) {
listnext(files[i]);
} else {
try {
if (files[i].getname().endswith(".java")) {
system.out.println(files[i].getabsolutepath());
javaline(files[i]);
}
}catch (exception e) {
e.printstacktrace();
}
}
}
}
/**
* 读取java文件总行数,代码行数,空白行数,注释行数
* @param f
* @throws ioexception
* @throws filenotfoundexception
*/
private static void javaline(file f) throws filenotfoundexception, ioexception{
string strline = "";
string str = fromfile(f);
if (str.length() > 0) {
while (str.indexof('\n') != -1) {
totle++;
//system.out.println(totle);
strline = str.substring(0, str.indexof('\n')).trim();
//str = str.substring(str.indexof('\n') + 1, str.length());
if (strline.length() == 0 ) {
blank++;
}else if (strline.charat(0) == '*' || strline.charat(0) == '/') {
comments++;
}else{
source++;
string regex = "^*//";
if(regex(strline,regex)){
comments++;
}
}
str = str.substring(str.indexof('\n') + 1, str.length());
}
}
}
/**
* 将java文件以字符数组形式读取
* @param f
* @return
* @throws filenotfoundexception
* @throws ioexception
*/
private static string fromfile(file f) throws filenotfoundexception,ioexception {
fileinputstream fis = new fileinputstream(f);
byte[] b = new byte[(int) f.length()];
fis.read(b);
fis.close();
return new string(b);
}
/**
* 正则匹配
* @param str 输入字符串
* @param regex 正则匹配字符串
* @return
*/
private static boolean regex(string str,string regex){
pattern p=pattern.compile(regex);
matcher m=p.matcher(str);
boolean result=m.find();
return result;
}
public static void main(string[] args) throws filenotfoundexception, ioexception {
//file root = new file(project_dir);
file directory = new file("");//参数为空
//获取项目路径
string projectfile = directory.getcanonicalpath() ;
system.out.println(projectfile+"===============");
listnext(new file(projectfile));
system.out.println(totle+1);
system.out.println(source);
system.out.println(blank);
system.out.println(comments);
}
}
上一篇: 关于mysql合并表的详细介绍
下一篇: 求最长递增子序列