本帖最后由 波-wang 于 2014-10-3 22:27 编辑
package io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Set;
import java.util.TreeMap;
public class CharCount {
public static void main(String[] args) throws IOException {
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
coutToMap(tm);
readMap(tm);
}
private static void readMap(TreeMap<Character, Integer> hm)
throws IOException {
FileOutputStream fos = new FileOutputStream("E:/课程/222.txt");
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(fos));
Set<Character> set = hm.keySet();
for (Character key : set) {
int num = hm.get(key);
String str = key + " : " + num + "次";
// System.out.println(str);
bufw.write(str);
bufw.newLine();
bufw.flush();
}
bufw.close();
}
private static void coutToMap(TreeMap<Character, Integer> hm)
throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("E:/课程/111.txt");
BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
/**
* 我的理解主要是这里有错误,
* 在记事本里写入数据时,我们并没有将记事本写满,
* 定义1024长度的数组时,因为数组长度不可变,
* 所以后面写入了很多空格
*/
char[] ch = new char[fis.available()];
while (bufr.read(ch) != -1) {
for (int i = 0; i < ch.length; i++) {
if (hm.containsKey(ch)) {
int count = hm.get(ch);
count++;
hm.put(ch, count);
} else {
hm.put(ch, 1);
}
}
}
bufr.close();
}
}
|