用java语言实现对文件中的某个字符串进行替换写一个工具类
时间: 2023-04-03 14:04:16 浏览: 76
好的,我可以回答这个问题。以下是一个用 Java 语言实现对文件中的某个字符串进行替换的工具类的示例代码:
```java
import java.io.*;
public class FileStringReplacer {
public static void replaceStringInFile(String filePath, String oldString, String newString) {
try {
File file = new File(filePath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", content = "";
while ((line = reader.readLine()) != null) {
content += line + "\n";
}
reader.close();
content = content.replaceAll(oldString, newString);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
System.out.println("替换完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你可以调用 `replaceStringInFile` 方法,传入文件路径、要替换的字符串和替换后的字符串,即可实现对文件中的某个字符串进行替换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)