67,541
社区成员
发帖
与我相关
我的任务
分享
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
public int getCount(String str,String filename){
int count=0;
File file=new File(filename);
BufferedReader reader=null;
String target="";
try {
reader=new BufferedReader(new FileReader(file));
String string="";
//每次读取一行
while((string=reader.readLine())!=null){
//把所有行连在一起,以防要查找的字符串因换行被截断
target=target+string;
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(target);
//如果文件中读取的字符串中有要计算的字符串,就替换,每次只替换一个
while(target.indexOf(str)!=-1){
target=target.replaceFirst(str, "try");
count++;
}
return count;
}
public static void main(String args[]){
ReadFile rf=new ReadFile();
//我试验的是一,文件里的内容就是你发帖的内容
System.out.println(rf.getCount("一", "C:/test.txt"));
}
}