import java.io.File;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
/**
* 统计字符出现次数
*
*
* <p>
*
* @author cs12110 2018年11月7日
* @see
* @since 1.0
*/
public class CharCounter {
public static void main(String[] args) {
// 这里可以放置你的输入文件路径代码
File file = new File("d://a.txt");
// 统计和显示统计数据
Map<String, Integer> countMap = count(file);
for (Map.Entry<String, Integer> each : countMap.entrySet()) {
System.out.println(each.getKey() + "'s = " + each.getValue());
}
}
/**
* 统计文件里面a-z不区分大小写的个数
*
* @param f
* 文件
* @return Map
*/
private static Map<String, Integer> count(File f) {
Map<String, Integer> countMap = new HashMap<>();
try {
RandomAccessFile raf = new RandomAccessFile(f, "rw");
// 逐行读取
String line = null;
while (null != (line = raf.readLine())) {
// 判断行里面的每一个字符
char[] arr = line.toCharArray();
for (char ch : arr) {
// 将a-z转换成大写的A-Z
if (ch >= 'a' && ch <= 'z') {
ch -= 32;
}
// 统计
if (ch >= 'A' && ch <= 'Z') {
String key = String.valueOf(ch);
Integer value = countMap.get(key);
if (value == null) {
value = 0;
}
countMap.put(key, value + 1);
}
}
}
// 关闭IO流
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
return countMap;
}
}
测试数据
a
B
c
D
A
B
b
测试结果
A's = 2
B's = 3
C's = 1
D's = 1