import java.io.*;
/**
* 写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数
*/
public class SumString {
public static void main(String[] args) {
System.out.println(sumString01(new File("d:/a.txt"), "100"));
System.out.println(sumString02(new File("d:/a.txt"), "100"));
}
//方法一:
static String sumString01(File file,String str){
BufferedInputStream bis = null;
int count = 0;
try {
bis = new BufferedInputStream(new FileInputStream(file.getPath()));
int temp = 0;
StringBuffer sb = new StringBuffer();
while ((temp = bis.read())!=-1){
sb.append((char)temp);
}
String s = sb.toString();
int index = 0;
while ((index = s.indexOf(str,index)) != -1)
{
count++;
System.out.println("第"+count+"次;索引是" + index);
index = index + str.length();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "字符串出现共:"+count+"次";
}
//方法二:
static String sumString02(File file,String str){
BufferedInputStream bis = null;
int count = 0;
try {
bis = new BufferedInputStream(new FileInputStream(file.getPath()));
int temp = 0;
StringBuffer sb = new StringBuffer();
while ((temp = bis.read())!=-1){
sb.append((char)temp);
}
String s1 = sb.toString();
String s2 = "";
int length = s1.split(str).length;
//判断文件末尾是否包含字符子串
if(s1.substring(s1.length()-3,s1.length()).contains(str)){
count=length;
}else {
count=length-1;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "字符串出现共:"+count+"次";
}
}