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

I would highly recommend using the Apache Common's FileUtil for this. I have found this package invaluable. It's easy to use and equally important it's easy to read/understand when you go back a while later.

//Create some files here
File sourceFile = new File("pathToYourFile");
File fileToCopy = new File("copyPath");

//Sample content
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");

//Now copy from source to copy, the delete source.
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);

More information can be found at: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html


Unless you're just adding content at the end, it's reasonable to do it that way. If you are appending, try FileWriter with the append constructor.

A slightly better order would be:

  1. Generate new file name (e.g. foo.txt.new)
  2. Write updated content to new file.
  3. Do atomic rename from foo.txt.new to foo.txt

Unfortunately, renameTo is not guaranteed to do atomic rename.


See: java.io.RandomAccessFile

You'll want to open a File read-write, so:

RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw");
String tmp;
while (tmp = raf.readLine() != null) {
    // Store String data
}
// do some string conversion
raf.seek(0);
raf.writeChars("newString");

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();