- package IOTest;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeMap;
- /*
- * 10.把当前文件中的所有文本拷贝,存入一个txt文件,统计每个字符出现的次数并输出
- */
- public class Test1 {
- public static void main(String[] args) {
- BufferedReader br=null;
- BufferedWriter bw=null;
- try {
- br=new BufferedReader(new FileReader("e:/q/info.txt"));
- bw=new BufferedWriter(new FileWriter("e:/q/inx.txt"));
- TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>(new Comp());
- int count=0;
- for (int i = 0; (i=br.read())!=-1;) {
- Integer value=tm.get((char)i);//获取集合中的值
- if(value!=null)//如果集合中没有该字母,则存入
- count=value;
- count++;
- tm.put((char)i,count);//存入键值对
- count=0;//复位计数变量
- }
-
- Iterator<Character> it=tm.keySet().iterator();
- while (it.hasNext()) {
- Character character = it.next();
- Integer it1=tm.get(character);
- bw.write(character+"("+it1+")");
-
- }
- bw.flush();
- } catch (IOException e) {
- throw new RuntimeException("读写文件失败");
- }finally{
- try {
- if (br==null) {
- br.close();
- }
- } catch (IOException e2) {
- throw new RuntimeException("读取流关闭失败");
- }
- try {
- if (bw==null) {
- bw.close();
- }
- } catch (IOException e2) {
- throw new RuntimeException("写入流关闭失败");
- }
- }
-
- }
-
- }
- class Comp implements Comparator<Character>{
- @Override
- public int compare(Character o1, Character o2) {
- return o1.compareTo(o2);
-
- }
-
- }
复制代码 最后文件是乱码!我只知道键可以正常写入。但加上值写入就乱码 不知道那里出现问题 求高手解答 谢谢!!!!!
|
|