场景: 统计wk
目录下所有的文件中包含指定字符
如:a文件包含("异常信息:【123】")
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
/**
* 解析目录下包含指定字符串的所有文件,提取指定字符串
*
* @author cancan.liu
* @version 1.0
* @date 2021/12/3 2:03 PM
* @since 1.0
*/
@Slf4j
public class ParseDirectoryFileRowValueUtil {
/**
* 完整路径
*
* @param folderPath
* @param fileName
* @return
*/
public static String makeFilePath(String folderPath, String fileName) {
return folderPath.endsWith("\\") || folderPath.endsWith("/") ? folderPath + fileName :
folderPath + File.separatorChar + fileName;
}
/**
* 递归遍历文件目录,获取所有文件路径
*
* @param filePath
*/
public static List<String> getAllFilePathFromFolder(String filePath) {
List<String> filePaths = new ArrayList<>();
File file = new File(filePath);
File[] tempFile = file.listFiles();
for (int i = 0; i < tempFile.length; i++) {
String tempFileName = tempFile[i].getName();
String path = makeFilePath(filePath, tempFileName);
if (tempFile[i].isFile()) {
filePaths.add(path);
} else {
List<String> tempFilePaths = getAllFilePathFromFolder(path);
if (tempFilePaths.size() > 0) {
for (String tempPath : tempFilePaths) {
filePaths.add(tempPath);
}
}
}
}
return filePaths;
}
public static void main(String args[]) throws Exception {
List<String> allFilePathFromFolder = getAllFilePathFromFolder("/Library/wk");
if (CollectionUtils.isEmpty(allFilePathFromFolder)) {
return;
}
// 结果输出到的路径
File writeName = new File("/Users/cancanliu/Downloads/tips.txt");
writeName.createNewFile();
// 文件写对象
try (FileWriter writer = new FileWriter(writeName); BufferedWriter out = new BufferedWriter(writer)) {
for (String filePath : allFilePathFromFolder) {
File file = new File(filePath);
// 文件读对象
try (BufferedReader br = new BufferedReader(new FileReader(file));) {
String tip;
while ((tip = br.readLine()) != null) {
if (tip.contains("\"【") && tip.contains("】") && tip.contains("\")") && !tip.contains("log.") && !tip.contains(".append")) {
int startIndex = tip.indexOf("\"【") + 1;
int endIndex = tip.indexOf("\")");
tip = tip.substring(startIndex, endIndex);
log.info(tip);
out.write(tip + "\r\n");
out.flush();
}
}
}
}
}
}
}