简单通过,文件字符流,读写文件,HashMap记录文字个数,最后用缓存流写出。qaq
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TextTotal {
public static void main(String[] args) {
FileReader fr = null;
BufferedWriter bw = null;
try {
Map<Character, Integer> map = new HashMap<>();
fr = new FileReader("待统计文本.txt");
int t = 0;
while ((t = fr.read()) != -1) {
char c = (char) t;
if (map.get(c) == null) {
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
bw = new BufferedWriter(new FileWriter("文字个数统计.txt"));
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
bw.write(new String(entry.getKey() + "=" + entry.getValue()));
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}