统计txt文件中出现的某个字符数


  

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class charCounts {
public static int process(File file, char c){
int count=0;
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(file));
String temp = "";
while((temp=br.readLine()) != null){
char[] des = temp.trim().toCharArray();
for(int i=0; i<des.length; i++){
if(des[i]==c){
count++;
}
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}

return count;
}

// 测试

1
2
3
4
5
6
7
8
9
    public static void main(String[] args){

String path = "D:/test.txt"; //或"D://test.txt"或"D:\\test.txt"
File file = new File(path);
char des = 'a';
int count = process(file,des);
System.out.println("字符"+des+"在文中出现的次数为:"+count);
}
}

---------------- The End ----------------
0%