问题
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