I'm looking for a way to replace a string in a file without reading the whole file into memory. Normally I would use a Reader and Writer, i.e. something like the following:
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();
}
Run Code Online (Sandbox Code Playgroud)
However, I want to do the replacement in-place, and don't think I can have a Reader and Writer open on the same file concurrently. Also, I'm using Java 1.4, so dont't have access to NIO, Scanner, etc.
Thanks, Don
Jak*_*org 31
"就地"通常不能替换文件,除非替换长度与原始长度完全相同.否则,文件需要增长,从而将所有后面的字节"向右"混乱,或缩小.执行此操作的常用方法是读取文件,将替换文件写入临时文件,然后使用临时文件替换原始文件.
这也具有以下优点:所讨论的文件始终处于原始状态或完全替换状态,从不介于两者之间.
| 归档时间: |
|
| 查看次数: |
22925 次 |
| 最近记录: |