IO练习:获取文件中的数据,数据排序,将排序后的数据写入文件。

💕前面的话💞
本篇是关于IO流的一个练习题:获取文件中的数据,然后进行数据排序,将排序后的数据写入文件中

✨欢迎关注🖱点赞🎀收藏⭐留言✒
😘系列专栏:java学习
🎨现在的播种,以后的收货
🀄如果觉得博主的文章还不错的话,请三连支持一下博主哦
package IO;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class TestIO {

   static HashMap<String, Integer> map = new HashMap<String, Integer>();
    public static void main(String[] args) throws IOException {
        File file=new File("F:/xiaoli.txt");
        File file1 = new File("F:/xiaoliu.txt");
        read(file);
        sort(map);
        wirte(file1);
    }


//读文件
    private static void read(File file) throws IOException {

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String str="";
        while((str=reader.readLine())!=null){
            String[] words = str.split(" ");
            for(String word :words){
                if (map.containsKey(word)){
                    Integer value = map.get(word);
                    map.put(word,value+1);
                }else{
                    map.put(word,1);
                }
            }
        }
        reader.close();

        Set<String> set = map.keySet();
        for (String s:set){
            Integer value = map.get(s);
            System.out.println(s+"\t\t的数量:"+value);
        }
    }


//写文件
    private static void wirte(File file) throws IOException {
        List<Entry<String, Integer>> list=sort(map);
        BufferedWriter bw=new BufferedWriter(new FileWriter(file));
//        Set<Entry<String, Integer>> entries = map.entrySet();

        for(Map.Entry<String,Integer> entry:list){
            bw.write(entry.getKey()+"\t"+entry.getValue());
            bw.newLine();
        }
        bw.flush();
    }


//排序
    private static List<Map.Entry<String, Integer>> sort(Map<String,Integer> map){
       List<Map.Entry<String,Integer>> list = new ArrayList(map.entrySet());
       Collections.sort(list, new Comparator<Entry<String, Integer>>() {
           public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
               return o1.getValue()-o2.getValue();
           }
       });
        System.out.println("---------------排序----------------");
        for(Map.Entry<String,Integer> stringIntegerEntry :list){
            System.out.println(stringIntegerEntry.getKey()+"\t"+stringIntegerEntry.getValue());
        }
        return list;
    }


}

原文件:
在这里插入图片描述

结果文件:
在这里插入图片描述

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值