Recreating a file and writing new contents
I am trying to delete a line from a text file in java, I have read around and it seems that there are a couple of solutions: delete the file and recreate it and write to it, or write to a temp file and rename it. It seems like both solutions involve closing streams, I may be missing something simple here but how do I use a writer with a file after I close it, is there something I can do to get a new writer up and running right after recreating or renaming the file so that I can modify the new file?
For example:
I have a file movies.txt, I save all the 开发者_如何学Golines in that file to a variable, close the streams on movies.txt, delete movies.txt and create movies.txt, how can I write to the new movies.txt after I closed the stream to it?
Or if I rename the file:
I have movies.txt, I create temp.txt and write everything from movies.txt to temp.txt, close streams on movies.txt, rename temp.txt to movies.txt, how do I write to movies.txt if the streams are closed?
Your temp file method might be easier. Say you want to delete the n-th line from a file, here are the steps you want to follow.
- Create a reader for the target file
- Create a writer to a temp file
- Read each line from source file and write to temp file <--- do this n-1 times
- Skip n-th line
- Read each line from source file and write to temp file till end of source file.
- Close source file reader and temp file writer.
- Delete source file and rename temp file to source file's name.
I'm thinking that you are thinking that if you reopened the file for writing, you would clobber its current contents.
That is generally true, but you can also open a file in write append mode; for example using this constructor.
FileOutputStream fos = new FileOutputStream("file.txt", true);
This causes output to be written to the end of a file, if it already exists.
(There are probably other ways to do this, but this is the simple way.)
精彩评论