package com.heima.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class Test {
/*
获取一个文本上每个字符出现的次数,将结果写在times.txt上
*/
public static void main(String[] args) throws Exception {
//使用输入流独享关联文件
BufferedReader br = new BufferedReader(new FileReader("LianXi2.java"));
int line = 0;
//创建map集合
Map<Character, Integer> map = new TreeMap<>();
while((line = br.read())!= -1){
char c = (char)line;
//将读取到的字符添加到map集合中
map.put(c, !map.containsKey(c) ? 1 : map.get(c) + 1);
}
br.close();
Set<Map.Entry<Character, Integer>> set = map.entrySet();
Iterator<Map.Entry<Character, Integer>> it = set.iterator();
BufferedWriter bw = new BufferedWriter(new FileWriter("times.txt"));
//遍历map集合
while(it.hasNext()){
Entry<Character, Integer> en = it.next();
Character key = en.getKey();
Integer value = en.getValue();
if(key.equals('\r')){
bw.write("\\r = " + value);
}else if(key.equals('\n')){
bw.write("\\n = " + value);
}else if(key.equals('\t')){
bw.write("\\t = " + value);
}else if(key.equals(' ')){
bw.write("空格 = " + value);
}else {
bw.write(key + " = " + value);
}
bw.newLine();
}
System.out.println("写入完成");
bw.close();
}
} |
|