本次实现方法为,将文本内容全读到缓存中去,读取的过程中如果包含目标字符串则替换后写入缓存,读取完后将缓存内容写入文本。
以下为代码实现过程:
public class AlterStringInFile {
private static String path ="src/源文件"; //目标文件路径
private static File file = new File(path); //创建目标文件
public static void alterStringToROM(String oldString,
String newString){
try {
long start = System.currentTimeMillis();
BufferedReader br_File = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
CharArrayWriter caw = new CharArrayWriter();
String string ;
int sum = 0;
while ((string = br_File.readLine()) != null){
//判断是否包含目标字符,包含则替换
if(string.contains(oldString)){
string = new String(string.replace(oldString, newString));
sum++;
}
//写入内容并添加换行
caw.write(string);
caw.write("\r\n");
}
br_File.close();
BufferedWriter bw_File = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(file)));
caw.writeTo(bw_File);
caw.close();
bw_File.close();
long time = System.currentTimeMillis() - start;
System.out.println(sum+"个"+oldString
+"替换成"+newString+"耗费时间:"+time);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
String oldString = "oldString";
String newString = "newString";
alterStringToROM(oldString, newString);
}
}