原文档内容1.png这里使用字符缓冲流BufferedReader逐行读取文档中的内容,利用split方法将每一行的字符与数字分离,然后将字符部分作为key值数字部分作为value值存入HashMap,在HashMap中按value值进行降序排序后利用转换流OutputStreamWriter将Map中的内容重新输出到文件中

    1. import java.io.BufferedReader;
    2. import java.io.File;
    3. import java.io.FileReader;
    4. import java.io.IOException;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. public class savefile {
    8. //将文件中的内容读入HashMap
    9. Map<String, Integer> fTM() {
    10. Map<String, Integer> map = new HashMap<String, Integer>();
    11. File file = new File("F:\\Java\\IO Study 03\\test.txt");
    12. BufferedReader reader = null;
    13. try {
    14. reader = new BufferedReader(new FileReader(file));
    15. String tempString = null;
    16. // 一次读入一行,直到读入null为文件结束
    17. while ((tempString = reader.readLine()) != null) {
    18. if(strArray.length > 1) {
    19. int ic = Integer.parseInt(strArray[1]);
    20. map.put(strArray[0], ic);
    21. }
    22. }
    23. reader.close();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. } finally {
    27. if (reader != null) {
    28. try {
    29. reader.close();
    30. } catch (IOException e1) {
    31. }
    32. }
    33. }
    34. return map;
    35. }
    36. }
    1. import java.util.*;
    2. public class MapSort {
    3. // Map按value值降序排序
    4. public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
    5. List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
    6. Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
    7. @Override
    8. public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
    9. int compare = (o1.getValue()).compareTo(o2.getValue());
    10. return -compare;
    11. }
    12. });
    13. Map<K, V> returnMap = new LinkedHashMap<K, V>();
    14. for (Map.Entry<K, V> entry : list) {
    15. returnMap.put(entry.getKey(), entry.getValue());
    16. }
    17. return returnMap;
    18. }
    19. }
    1. import java.io.FileOutputStream;
    2. import java.io.IOException;
    3. import java.io.OutputStreamWriter;
    4. import java.util.Map;
    5. public class save {
    6. public static void saveMapToTxt(Map<String, Integer> map, String filePath){
    7. OutputStreamWriter outFile = null;
    8. FileOutputStream fileName;
    9. try{
    10. fileName = new FileOutputStream(filePath);
    11. outFile = new OutputStreamWriter(fileName);
    12. String str = "";
    13. for(String key : map.keySet()){
    14. str += key + "-----------------------------------" + map.get(key) + "\n";
    15. }
    16. outFile.write(str);
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }finally{
    20. try {
    21. outFile.flush();
    22. outFile.close();
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. }
    28. }

    排序后的文档内容
    2.png