Java - delete line from text file by overwriting while reading it

后端 未结 3 1858
离开以前
离开以前 2020-11-27 07:59

I\'m trying to delete a line of text from a text file without copying to a temporary file. I am trying to do this by using a Printwriter and a Scanner and having them traver

3条回答
  •  失恋的感觉
    2020-11-27 09:00

    You cannot do it this way. FileWriter can only append to a file, rather than write in the middle of it - You need RandomAccessFile if you want to write in the middle. What you do now - you override the file the first time you write to it (and it gets empty - that's why you get the exception). You can create FileWriter with append flag set to true - but this way you would append to a file rather than write in the middle of it.

    I'd really recommend to write to a new file and then rename it at the end.

提交回复
热议问题