题5

题目描述:有两个文件,文件每一行是一个访问IP,请将两个文件合并成一个文件,新文件中每一行有两个字段:IP和IP出现的总次数,并按IP的出现的总次数降序排序。
例:
文件a:
100.1.2.3
200.1.2.3
192.168.0.1

文件b:
200.1.2.3
192.168.0.1
192.168.0.1
合并后得到的新文件c:
192.168.0.1 3
200.1.2.3 2
100.1.2.3 1

代码:

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String patha="C://a.txt";
        String pathb="C://b.txt";
        HashMap<String,Integer> map=new HashMap<>();
        getMap(patha,map);
        getMap(pathb,map);
        List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        StringBuffer sb=new StringBuffer();
        for(Map.Entry<String,Integer> e:list){
            System.out.println(e.getKey()+"----->"+e.getValue());
            sb.append(e.getKey()+" "+e.getValue()+"\r\n");
        }
        try {
            FileWriter writer=new FileWriter("C://c.txt");
            BufferedWriter bw=new BufferedWriter(writer);
            bw.write(sb.toString());
            bw.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getMap(String path,Map<String,Integer> map){
        BufferedReader br=null;
        try {
            InputStream is=new FileInputStream(path);
            br=new BufferedReader(new InputStreamReader(is));
            String line="";
            while((line=br.readLine())!=null){
                line=line.trim();
                if(!map.containsKey(line)){
                    map.put(line,1);
                }else map.put(line,map.get(line)+1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值