import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
* 写一个代码统计一个小的文件中出现的所有的字符及其个数,例如,
* 对于文 件内容为“abcd”统计的结果类似于:
* a(1个), b(1个),c(1个), d(1个)。
*/
public class Statistics {
public static void main(String[] args) {
String file = "D://FTP//test4.txt";
Print1(file);
}
public static void Print1(String file) {
try (
BufferedReader br = new BufferedReader(new FileReader(file));
){
StringBuilder sb = new StringBuilder();
while(br.readLine() != null) {
sb.append(br.readLine());
}
char[] arr = sb.toString().toCharArray();
Map<Character,Integer> map = new HashMap<>();
for(char c : arr) {
if(!map.containsKey(c)) {
map.put(c, 1);
}else {
map.put(c, map.get(c)+1);
}
}
map.forEach((key,value) -> System.out.print(key+"("+map.get(key)+"个)"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
统计一个小的文件中出现的所有的字符及其个数
猜你喜欢
转载自blog.csdn.net/weixin_42131843/article/details/105025502
今日推荐
周排行