public class Tesyt {
public static int getKeyStringCount(String str, String key) {
int count = 0;
int index = 0;
while((index = str.indexOf(key,index))!=-1){
index = index + key.length();
count++;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("E:/Walden.txt");
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
int len = 0;
byte[] buf = new byte[1024];
String str = null;
while((len = fis.read(buf)) !=-1){
str = new String(buf, 0, len,"utf8");
}
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要查询字符串:");
String key = sc.nextLine();
int count = getKeyStringCount(str,key);
System.out.println("文件中此字符串出现次数为:"+count+"次");
}catch(FileNotFoundException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
请输入你要查询字符串:
Hello
文件中此字符串出现次数为:4次