Github項目地址:https://github.com/softwareCQT/web_camp/tree/master/wordCount
一、題目描述
-
實現一個簡單而完整的軟件工具(源程序特征統計程序)。
-
進行單元測試、回歸測試、效能測試,在實現上述程序的過程中使用相關的工具。
-
進行個人軟件過程(PSP)的實踐,逐步記錄自己在每個軟件工程環節花費的時間。
二、WC 項目要求
-
wc.exe 是一個常見的工具,它能統計文本文件的字符數、單詞數和行數。這個項目要求寫一個命令行程序,模仿已有wc.exe 的功能,並加以擴充,給出某程序設計語言源文件的字符數、單詞數和行數。
-
實現一個統計程序,它能正確統計程序文件中的字符數、單詞數、行數,以及還具備其他擴展功能,並能夠快速地處理多個文件。
-
具體功能要求:程序處理用戶需求的模式為:wc.exe [parameter] [file_name]
三、核心代碼
-
文件處理(包括處理通配符*?和-s遞歸)
/**
* @author chenqiting
*/
public class FileUtil {
/***
* 判斷文件是否合法 且 處理通配符並返回文件列表
* @return List<File>
*/
public static List<File> accessRegx(String fileName){
if (fileName.contains(CommandConstants.UNIVERSAL_CHAR_ONE)
|| fileName.contains(CommandConstants.UNIVERSAL_CHAR_TWO)) {
//判斷是否存在通配符,統一換掉參數
fileName = fileName.
replace(CommandConstants.UNIVERSAL_CHAR_TWO, CommandConstants.UNIVERSAL_CHAR_ONE);
//如果是絕對路徑,獲取絕對路徑的前半段,即獲取到*號之前的路徑
int index = fileName.indexOf("*");
//標志文件是否在文件后綴加的通配符
boolean flag = (index == fileName.length() - 1);
String parentDirectory;
String childFileName;
//如果是文件類型通配符,父路徑需要重新處理
if (flag) {
index = fileName.lastIndexOf("\\");
index = index == -1 ? 0 : index;
}
parentDirectory = fileName.substring(0, index);
childFileName = fileName.substring(index);
//系統路徑匹配器
PathMatcher pathMatcher;
File file;
//空字符串表示需要當前路徑匹配
if ("".equals(parentDirectory)){
file = new File(".");
String string = file.getAbsolutePath().replace(".", "").replace("\\", "\\\\");
file = new File(string);
pathMatcher = FileSystems.getDefault().
getPathMatcher("regex:" + string + "\\\\" + childFileName);
}else {
parentDirectory = parentDirectory.replace("\\", "\\\\");
file = new File(parentDirectory);
//在parentDirectory目錄下進行遍歷
pathMatcher = FileSystems.getDefault().
getPathMatcher("glob:" + parentDirectory + childFileName);
}
return stackForFile(file, pathMatcher);
}else {
File file = new File(fileName);
//判斷文件是否存在
if (file.exists()){
if (file.isDirectory()){
System.out.println(file.getName() + "不是文件,請重新輸入");
}
}else {
System.out.println("找不到該文件");
}
ArrayList<File