Is this the best way to rewrite the content of a file in Java?

file-io, java, url-rewriting

Solution

To overwrite file foo.log with FileOutputStream:

File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
                                                                 // false to overwrite.
byte[] myBytes = "New Contents\n".getBytes(); 
fooStream.write(myBytes);
fooStream.close();

or with FileWriter :

File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
                                                     // false to overwrite.
fooWriter.write("New Contents\n");
fooWriter.close();

Problem

I want to rewrite the contents of a file. What I have thought of so far is this: - Save the file name - Delete the existing file - Create a new empty file with the same name - Write the desired content to the empty file Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content?

Original source

Related problems