替换文件中的字符串
我正在寻找一种方法来替换文件中的字符串,而无需将整个文件读取到内存中。通常我会使用读取器和写入器,即如下所示:
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();
}
但是,我想就地进行替换,并且不认为我可以同时在同一文件上打开读取器和写入器。另外,我使用的是Java 1.4,所以无法访问NIO,Scanner等。
谢谢 唐