import java.io.*;
/**文本文件的扫描和替换功能
*@author 太黑
*/
public class FindAndRplace {
/**对文档进行扫描,返回文档内存在str的个数*/
public static int find(String fileName, String str) throws IOException {
File f=new File(fileName);
BufferedReader br=new BufferedReader(new FileReader(f));
String s;
int count=0;
while((s=br.readLine())!=null){
if (s.contains(str)) {
String[] st=s.split(str,-1);
//按照str关键对提取出来的字符串进行数组分割(-1)是代表关键字若在末尾也依然会添加计数进入数组
count+=st.length-1;
}
}
br.close();
return count;
}
public static int replace(String fileName, String str, String newStr) throws IOException {
File f=new File(fileName);
BufferedReader br=new BufferedReader(new FileReader(f));
String s="",s1 = "";
int count=0;
while((s=br.readLine())!=null){
s1+=s+"\r\n";
if (s.contains(str)) {
String[] st=s.split(str,-1);
count+=st.length-1;
}
}
FileWriter fw=new FileWriter(f);
fw.write(s1.replace(str, newStr));
br.close();
fw.close();
return count;
}
转载于:https://my.oschina.net/2892328252/blog/644542