实现:
利用java代码统计日志文件中字符串出现的数量
直接贴代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class findFolderText {
public static void main(String[] args) {
File folder = new File("X:\\临时文件夹\\文件\\nginx日志");
List<String> strings = new ArrayList<>();
strings.add("api");
for (String string : strings) {
int count = 0;
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
count += searchInFile(file, string);
}
}
}
System.out.println("The search string '" + string + "' is found " + count + " times in the files.");
}
}
public static int searchInFile(File file, String searchString) {
int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchString)) {
count++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
}