统计一个文件中字符串出现的次数,并且输出出现次数最多的字符串的个数和字符串
import java.util.*;
import java.io.*;
public class Test1 {
public static void main(String []args){
FileInputStream fis = null;
File file = new File("E:\\Walden.txt");
HashMap<String, Integer> map = new HashMap<>();
try{
fis = new FileInputStream(file);
byte []b = new byte[1024];
int len = 0;
String str = "";
while((len = fis.read(b)) != -1){
str += new String(b, 0, len);
}
String resString = count(str, map);
int resCount = map.get(resString);
System.out.println("出现次数最多的字符串是"+resString+", 其出现次数是"+resCount);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
fis.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public static String count(String str, HashMap<String, Integer> map){//返回文本文件中出现次数最多的字符串
String []s = str.split(" ");
String result = s[0];
for(String i: s){
if(!map.containsKey(i)){map.put(i, 1);}
else{
map.put(i, map.get(i)+1);
}
}
for(String i: map.keySet()){
if(map.get(i)>map.get(result)){result = i;}
}
return result;
}
}
总结
笨办法,欢迎批评指正!