獲取文本上字符出現的次數,把數據寫入文件-Java 集合方法Map

 

* 目的 :  獲取文本上字符出現的次數,把數據寫入文件
*
* 思路 :
* 1.遍歷文本每一個字符

*
* 2.字符出現的次數存在Map中
*
* Map<Character,Integer> map = new HashMap<Character,Integer>();
* map.put('a',18);
* map.put('你',2);
*
* 3.把map中的數據寫入文件

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class WordCount {
    /*
    說明:如果使用單元測試,文件相對路徑爲當前module
          如果使用main()測試,文件相對路徑爲當前工程
     */
    @Test
    public void testWordCount() {
        FileReader fr = null;
        BufferedWriter bw = null;
        try {
            //1.創建Map集合
            Map<Character, Integer> map = new HashMap<Character, Integer>();

            //2.遍歷每一個字符,每一個字符出現的次數放到map中
            fr = new FileReader("dbcp.txt");
            int c = 0;
            while ((c = fr.read()) != -1) {
                //int 還原 char
                char ch = (char) c;
                // 判斷char是否在map中第一次出現
                if (map.get(ch) == null) {
                    map.put(ch, 1);
                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }

            //3.把map中數據存在文件count.txt
            //3.1 創建Writer
            bw = new BufferedWriter(new FileWriter("wordcount.txt"));

            //3.2 遍歷map,再寫入數據
            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Character, Integer> entry : entrySet) {
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\t'://\t表示tab 鍵字符
                        bw.write("tab鍵=" + entry.getValue());
                        break;
                    case '\r'://
                        bw.write("回車=" + entry.getValue());
                        break;
                    case '\n'://
                        bw.write("換行=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.關流
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章