Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to rewrite the contents of a file.

What I have thought of so far is this:

  1. Save the file name
  2. Delete the existing file
  3. Create a new empty file with the same name
  4. 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?

like image 986
Ankur Avatar asked Jun 19 '09 03:06

Ankur


People also ask

What is the best way to write to a file in Java?

FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.


2 Answers

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(); 
like image 106
Stobor Avatar answered Sep 22 '22 03:09

Stobor


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

like image 40
jnt30 Avatar answered Sep 23 '22 03:09

jnt30