我正在寻找一种方法来替换文件中的字符串,而无需将整个文件读入内存。通常我会用一个读者与作者,也就是类似如下:替换文件中的字符串
public static void replace(String oldstring, String newstring, File in, File out)
throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(in));
PrintWriter writer = new PrintWriter(new FileWriter(out));
String line = null;
while ((line = reader.readLine()) != null)
writer.println(line.replaceAll(oldstring,newstring));
// I'm aware of the potential for resource leaks here. Proper resource
// handling has been omitted in the interest of brevity
reader.close();
writer.close();
}
然而,我想要做的就地更换,并且不认为我可以在同一个开放的Reader和Writer文件并发。另外,我使用Java 1.4,所以dont't访问NIO,扫描仪等
谢谢, 唐
只是FYI,你知道'replaceAll'是基于正则表达式的,对吧?如果你只是想直接进行字符串替换(如你的形式参数名称所示),你可以使用replace(CharSequence,CharSequence)方法。 – polygenelubricants 2010-06-30 08:40:26
如何写入临时文件然后替换原文件? – InsertNickHere 2010-06-30 08:40:45