Find a line in a file and remove it

后端 未结 16 1918
谎友^
谎友^ 2020-11-22 13:06

I\'m looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following

16条回答
  •  半阙折子戏
    2020-11-22 13:58

    You want to do something like the following:

    • Open the old file for reading
    • Open a new (temporary) file for writing
    • Iterate over the lines in the old file (probably using a BufferedReader)
      • For each line, check if it matches what you are supposed to remove
      • If it matches, do nothing
      • If it doesn't match, write it to the temporary file
    • When done, close both files
    • Delete the old file
    • Rename the temporary file to the name of the original file

    (I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)

提交回复
热议问题