小内存读取大文件实战
内存只有1M但是读取1G的文件并对出现字符的频率排序top5
- 获取文件
- 定义每次读取文件的大小
- 通过BufferedReader获取根据每次读取1m文件
- 每次读取一行,并放到hashMap中
- 遍历map并排序
public class topCharactorCounter {
public static void main(String[] args) {
File file = new File("E:\\1.txt");
int memoryLimit=1024*1024;
int bufferSize=1024;
Map<Character,Integer> chmap=new HashMap<>();
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader=new BufferedReader(fileReader);
String line;
while ((line=bufferedReader.readLine())!=null){
if (!line.trim().isEmpty()){
for (char c:line.toCharArray()){
chmap.put(c,chmap.getOrDefault(c,0)+1);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
int topCount=5;
for (int i = 0; i < topCount; i++) {
char topChar=' ';
int max=0;
for (Map.Entry<Character,Integer> entry:chmap.entrySet()){
if (entry.getValue()>max){
max=entry.getValue();
topChar=entry.getKey();
}
}
System.out.print(topChar+":"+max+" ");
chmap.remove(topChar);
}
}
}