package kryoDemo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class ReadFile {
public static String readFile(File file) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tmpStr = null;
// 一次读入一行,直到读入null为文件结束
while ((tmpStr = reader.readLine()) != null) {
sb.append(System.lineSeparator() + tmpStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
public static void main(String[] args) {
File file = new File("E:/errlog.txt");
if (!file.isFile() || !file.exists()) {
throw new RuntimeException("not File Or file is not exist");
}
String str = readFile(file);
String[] strArray = str.split(" |,");
Map<String, Integer> m = new LinkedHashMap<String, Integer>(str.length());
for (String detail : strArray) {
m.put(detail, m.containsKey(detail) ? m.get(detail) + 1 : 1);
}
String maxStr = null;
Integer maxNum = 0;
for (Entry<String, Integer> entry : m.entrySet()) {
if (entry.getValue() > maxNum) {
maxNum = entry.getValue();
maxStr = entry.getKey();
}
}
System.out.println(maxStr);
}
}
读取文件中出现次数最多的字符串
最新推荐文章于 2021-05-18 21:48:22 发布