面试:小内存读取大文件实战

本文介绍了一个Java程序,如何在内存限制为1MB的情况下,通过BufferedReader逐行读取1GB文件,统计每个字符出现的频率,并输出出现次数最多的前5个字符。
摘要由CSDN通过智能技术生成

小内存读取大文件实战

内存只有1M但是读取1G的文件并对出现字符的频率排序top5

  1. 获取文件
  2. 定义每次读取文件的大小
  3. 通过BufferedReader获取根据每次读取1m文件
  4. 每次读取一行,并放到hashMap中
  5. 遍历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);
        }
    }
}
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值