原文档内容
这里使用字符缓冲流BufferedReader逐行读取文档中的内容,利用split方法将每一行的字符与数字分离,然后将字符部分作为key值数字部分作为value值存入HashMap,在HashMap中按value值进行降序排序后利用转换流OutputStreamWriter将Map中的内容重新输出到文件中
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.HashMap;import java.util.Map;public class savefile {//将文件中的内容读入HashMapMap<String, Integer> fTM() {Map<String, Integer> map = new HashMap<String, Integer>();File file = new File("F:\\Java\\IO Study 03\\test.txt");BufferedReader reader = null;try {reader = new BufferedReader(new FileReader(file));String tempString = null;// 一次读入一行,直到读入null为文件结束while ((tempString = reader.readLine()) != null) {if(strArray.length > 1) {int ic = Integer.parseInt(strArray[1]);map.put(strArray[0], ic);}}reader.close();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}return map;}}
import java.util.*;public class MapSort {// Map按value值降序排序public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());Collections.sort(list, new Comparator<Map.Entry<K, V>>() {@Overridepublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {int compare = (o1.getValue()).compareTo(o2.getValue());return -compare;}});Map<K, V> returnMap = new LinkedHashMap<K, V>();for (Map.Entry<K, V> entry : list) {returnMap.put(entry.getKey(), entry.getValue());}return returnMap;}}
import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.util.Map;public class save {public static void saveMapToTxt(Map<String, Integer> map, String filePath){OutputStreamWriter outFile = null;FileOutputStream fileName;try{fileName = new FileOutputStream(filePath);outFile = new OutputStreamWriter(fileName);String str = "";for(String key : map.keySet()){str += key + "-----------------------------------" + map.get(key) + "\n";}outFile.write(str);} catch (IOException e) {e.printStackTrace();}finally{try {outFile.flush();outFile.close();} catch (IOException e) {e.printStackTrace();}}}}
排序后的文档内容
