其他分享
首页 > 其他分享> > 获取文本上每个字符的出现的次数,并写入到另一个文本里

获取文本上每个字符的出现的次数,并写入到另一个文本里

作者:互联网

获取文本上每个字符的出现的次数,并写入到另一个文本里(java实现)

import java.io.*;
import java.nio.Buffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Exer {
    public static void main(String[] args) {
            FileReader fr = null;
            FileWriter fw = null;
            try {
                fr = new FileReader("hello.txt");//此处填想要识别的文件路径

                HashMap<Character,Integer> hashMap = new HashMap<>();
                int len;
                while((len = fr.read()) != -1){
                    char ch = (char) len;
                    if(hashMap.get(ch) == null){
                        hashMap.put(ch,1);
                    }else {

                        hashMap.put(ch,hashMap.get(ch)+1);
                    }
                }


                //把map中数据存在文件count.txt中
                fw = new FileWriter(new File("count.txt"));//此处填想要输出的文件路径
                Set<Map.Entry<Character, Integer>> entrySet = hashMap.entrySet();
                for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
                    switch (entry.getKey()){
                        case ' ':
                            fw.write("空格=" + entry.getValue());
                            System.out.println("空格=" + entry.getValue());
                            break;
                        case '\t':
                            fw.write("tab键=" + entry.getValue());
                            System.out.println("tab键=" + entry.getValue());
                            break;
                        case '\r':
                            fw.write("回车=" + entry.getValue());
                            System.out.println("回车=" + entry.getValue());
                            break;
                        case '\n':
                            fw.write("换行=" + entry.getValue());
                            System.out.println("换行=" + entry.getValue());
                            break;
                        default:
                            fw.write(entry.getKey() +"="+ entry.getValue());
                            System.out.println(entry.getKey()+ "=" + entry.getValue());
                            break;

                    }
                    fw.write("\n");
                }


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



        }
    }

标签:字符,java,hashMap,fw,写入,getValue,write,entry,文本
来源: https://blog.csdn.net/Connor66/article/details/121181650