Replace string in file

后端 未结 2 1379
一个人的身影
一个人的身影 2020-12-03 10:06

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:

2条回答
  •  天命终不由人
    2020-12-03 11:10

    Replacing something in a file or stream requires a Writer or OutputStream which is capable of deleting and inserting bytes at any position. A replace operation can be split into a delete and an insert operation.

    Looking at the API of OutputStream and Writer I can't find suitable methods. One could use OutputStream to write bytes with an offset but this will simply overwrite existing context. So it could work for the special case, that original and replacement have the equal length.

    So right now I think, writing the edited lines to a temporary file and replacing the orignal file with the temp file afterwards is still the best solution.

提交回复
热议问题