暂时只能想到这个方法了。。。。。你参考下
package luntan;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class TestDemo {
/**
* @param args
* @throws IOException
*/
/*
* 需求: 统计一个文本文件中字符出现的次数,结果存入另外的一个文本文件中 1.统计字符出现的次数,这个可以根据之前学的map集合
* 2.将统计次数根据io流存储到另一个文本中
*/
public static void main(String[] args) throws IOException {
// 将文本文件封装
File file = new File("f:\\test.txt");
// 读取文本文件
String str = read(file);
String s = getCharCount(str);
// 将计数好的字符存储到另一个文件
cunFile(s);
}
public static void cunFile(String str) throws IOException {
File dir = new File("f:\\");
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
FileOutputStream fos = new FileOutputStream(new File(dir, "test2.txt"));
byte[] buf = new byte[1024];
int len = 0;
while ((len = bis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
bis.close();
}
public static String getCharCount(String str) {
// 字符串转换成字符数组
char[] chs = str.toCharArray();
// 定义map集合
Map<Character, Integer> map = new TreeMap<Character, Integer>();
for (int i = 0; i < chs.length; i++) {
// 排除字符串出现其他的字符
if (chs[i] >= 'a' && chs[i] <= 'z' || chs[i] >= 'A'
&& chs[i] <= 'Z') {
// 将字符转转成的字符数组,作为key,获取value
Integer value = map.get(chs[i]);
int count = 1;
if (value != null) {
count = value + 1;
}
// 替换后的key和value
map.put(chs[i], count);
}
}
return mapToString(map);
}
public static String mapToString(Map<Character, Integer> map) {
StringBuilder sb = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while (it.hasNext()) {
Character key = it.next();
Integer value = map.get(key);
sb.append(key + ":" + value + "\r\n");
}
return sb.toString();
}
public static String read(File file) throws IOException {
FileReader fr = new FileReader(file);
char[] buf = new char[1024];
int len = fr.read(buf);
String str = new String(buf, 0, len);
return str;
}
}
|