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

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

Leave a Comment