💕前面的话💞
本篇是关于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;
}
}
原文件:
结果文件: