从指定目录查找给定字符串是否存在
从指定文件夹读取文件
/**
* 从指定文件夹读取文件
*
* @param sourcePath 指定的源文件夹路径
* @param list x
* @throws Exception x
*/
public static void getFilesFromPath(String sourcePath, List<File> list) throws Exception {
// 目标集合fileList
File file = new File(sourcePath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File fileIndex : files) {
// 如果这个文件是目录,则进行递归搜索
if (fileIndex.isDirectory()) {
getFilesFromPath(fileIndex.getPath(), list);
} else {
// 如果文件是普通文件,则将文件句柄放入集合中
String fileName = fileIndex.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if ("java".equals(suffix) || "xml".equals(suffix)) {
list.add(fileIndex);
}
}
}
}
}
从文件中查找匹配
/**
* 在文件中查找匹配的
*
* @param fileList 遍历文件集合
* @param regexStringList 匹配字符串集合
* @return 匹配的字符串集合
* @throws IOException e
*/
public static Set<String> findStringInFileList(List<File> fileList, List<String> regexStringList) throws IOException {
Set<String> existStrSet = new HashSet<>();
for (String regexStr : regexStringList) {
boolean isHas = false;
for (File file : fileList) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// 指定字符串转成大写判断
if(line.toUpperCase().contains(regexStr.toUpperCase())){
isHas = true;
};
if(isHas){
break;
}
}
if(isHas){
break;
}
}
if (isHas) {
existStrSet.add(regexStr);
continue;
}
}
return existStrSet;
}