java對象類之完成java獲得文件行數。本站提示廣大學習愛好者:(java對象類之完成java獲得文件行數)文章只能為提供參考,不一定能成為您想要的結果。以下是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);
}
}