Replace string in file

后端 未结 2 1376
一个人的身影
一个人的身影 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:00

    "In place" replacing usually isn't possible for files, unless the replacement is exactly the same length as the original. Otherwise the file would need to either grow, thus shuffling all later bytes "to the right", or shrink. The common way of doing this is reading the file, writing the replacement to a temporary file, then replacing the original file with the temporary.

    This also has the advantage that the file in question is at all times either in the original state or in the completely replaced state, never in between.

提交回复
热议问题