java文本文件查找替换需用字符流逐行读写,必须通过临时文件原子替换原文件以保安全;核心是bufferedreader+inputstreamreader读取(指定utf-8编码防乱码),string.replace()替换后由bufferedwriter+outputstreamwriter写入临时文件,最后files.move原子覆盖。

Java 中用字符流实现文本文件的查找与替换,核心是用 InputStreamReader 和 OutputStreamWriter(配合 FileReader/FileWriter)逐行读取、处理并写回。不能直接在原文件上“就地替换”,必须读入内存修改后写入新文件(或先写临时文件再替换原文件)。
读取文件内容并逐行处理
使用 BufferedReader 包装 FileReader,按行读取更高效且避免乱码:
- 指定字符编码(如
"UTF-8"),防止中文乱码; - 每读一行,用
String.replace()或String.replaceAll()替换目标字符串; -
replace()替换字面量,replaceAll()支持正则,注意特殊字符需转义。
写入替换后的内容到新文件
用 BufferedWriter 包装 FileWriter 写入结果:
- 建议使用
new FileWriter(file, false)(false表示覆盖写入); - 每处理完一行就调用
write()+newLine(),保证换行符一致; - 操作完成后务必调用
close()或使用 try-with-resources 自动释放资源。
安全替换:先写临时文件再原子替换
为防止替换失败导致原文件损坏,推荐“临时文件 + 文件替换”策略:
- 将处理后的内容写入一个临时文件(如
file.tmp); - 写入成功后,用
Files.move(tempPath, originalPath, StandardCopyOption.REPLACE_EXISTING)原子替换原文件; - 若出错,保留原文件不变,临时文件可手动清理。
完整示例代码(含编码与异常处理)
以下是一个简洁可用的实现:
public static void replaceInFile(String filePath, String target, String replacement)
throws IOException {
Path path = Paths.get(filePath);
Path tempPath = Files.createTempFile("replace_", ".tmp");
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(tempPath, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line.replace(target, replacement));
writer.newLine();
}
}
Files.move(tempPath, path, StandardCopyOption.REPLACE_EXISTING);
}
调用方式:replaceInFile("a.txt", "old", "new");
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











