import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
//1.获取一个文本文件上每个字符出现的次数,将结果写在times.txt上
public class CharTimes {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件路径:");
String str = scanner.nextLine();
File file = new File(str);
if (file.isDirectory()) {
System.out.println("输入的文件路径有误!");
return;
} else {
countCharForFile(file);
}
}
private static void countCharForFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
Map<Character, Integer> hashMap = new HashMap<Character, Integer>();
String len;
while ((len = br.readLine()) != null) {
char[] chars = len.toCharArray();
for (char thisChar : chars) {
if (!hashMap.containsKey(thisChar)) {
hashMap.put(thisChar, 1);
} else {
hashMap.put(thisChar, hashMap.get(thisChar) + 1);
}
}
}
//便利集合 得到重复字符和次数的关系 并调用BufferedWrite.write()方法写入a.txt
Set<Entry<Character, Integer>> entrySet = hashMap.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
bw.write(entry.getKey()+"出现的次数是"+entry.getValue());
}
br.close();
bw.close();
}
} |
|