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如何实现搜索结果分类
- 下一篇: 20155216 2016-2017-2