Java IO流练习题-获取文本上每个字符出现的次数
生活随笔
收集整理的這篇文章主要介紹了
Java IO流练习题-获取文本上每个字符出现的次数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
獲取文本上每個字符出現的次數
提示:遍歷文本的每一個字符;字符及出現的次數保存在Map中;將Map中數據寫入文件
package BYSSSExer2;import org.junit.Test;import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Set;/*** @author Baiysmart* @create 2020-03-28 10:57*/ /*獲取文本上字符出現的次數,并把數據寫入文件1 遍歷文本每一個字符2 字符出現的次數存在Map中3 把Map中的數據寫入文件*/ public class WordCountTest {@Testpublic void testWordCount() throws IOException {//創建Map集合Map<Character,Integer> map = new HashMap<>();//2 遍歷每一個字符,每個字符出現的次數放到map中FileReader fr = new FileReader("hello.txt");int c = 0;while ((c = fr.read())!=-1){//int 還原 charchar 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 創建WriterBufferedWriter bw = new BufferedWriter(new FileWriter("count.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' :bw.write("tab="+entry.getValue());break;case '\n' :bw.write("換行="+entry.getValue());break;default:bw.write(entry.getKey()+"="+entry.getValue());break;}bw.newLine();}fr.close();bw.close();} }
總結
以上是生活随笔為你收集整理的Java IO流练习题-获取文本上每个字符出现的次数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lucene.Net如何实现搜索结果分类
- 下一篇: Spring入门hello world常