// 查找并替换文本中的字符串 |
/** |
* @param searchText 被替换的字符串 |
* @param replaceText 新的字符串 |
* @param path 文件路径 |
* @throws IOException |
*/ |
public static void ReplaceWord(String searchText, String replaceText, String path) throws IOException { |
if (searchText.isEmpty()) |
return ; |
File file = new File(path); |
InputStreamReader fis = new InputStreamReader( new FileInputStream(file), "UTF-8" ); |
// FileReader fis = new FileReader(file);// 创建文件输入流 |
char [] data = new char [ 1024 ]; // 创建缓冲字符数组 |
int rn = 0 ; |
StringBuilder sb = new StringBuilder(); // 创建字符串构建器 |
while ((rn = fis.read(data)) > 0 ) { // 读取文件内容到字符串构建器 |
String str = String.valueOf(data, 0 , rn); |
sb.append(str); |
} |
fis.close(); // 关闭输入流 |
// 从构建器中生成字符串,并替换搜索文本 |
String str = sb.toString().replace(searchText, replaceText); |
OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(file), "UTF-8" ); |
out.write(str.toCharArray()); |
out.flush(); |
out.close(); |
} |