How to delete a line in a .txt file using FileOutputStream?

丶灬走出姿态 提交于 2021-02-10 08:43:15

问题


I need to delete a line from a .txt file stored in the android device's internal storage. I am using

FileOutputStream fos = context.openFileOutput("file.txt", Context.MODE_APPEND);

to open the .txt file. I already know the line which is to be deleted. How to delete it? Sorry if this question is easy, I looked and couldn't find an answer on Google.


回答1:


You can't easily remove a line of text from a file. You can overwrite it with other data which contains the same number of characters, but basically files don't support removing data from arbitrary locations in a file.

You probably want to:

  • Create a reader for the existing file
  • Create a writer for a new file
  • Copy one line at a time, skipping the line you want to delete
  • Close both the reader and the writer
  • Rename the old file out of the way
  • Rename the new file to the old filename
  • Delete the renamed old file

(Those steps make sure that even if something goes wrong, you never lose data.)



来源:https://stackoverflow.com/questions/17022387/how-to-delete-a-line-in-a-txt-file-using-fileoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!