50

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ankur
  • 50,282
  • 110
  • 242
  • 312

8 Answers8

94

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();
pmartin8
  • 1,545
  • 1
  • 20
  • 36
Stobor
  • 44,246
  • 6
  • 66
  • 69
  • @Ankur: yeah. It depends on whether you're writing strings or binary stuff in bytes as to whether you'd use the OutputStream or the Writer approach. – Stobor Jun 19 '09 at 04:32
  • Is there any method available for pdf file writer without changing it's name? – BobDroid Jan 06 '12 at 04:49
  • @BabuThangavel I'm not sure what you're asking, but it doesn't look like it's related to this question... Maybe you want to ask a new question? – Stobor Jan 09 '12 at 04:27
  • Do you need to close the File object after closing the FileWriter? – AnnanFay Nov 19 '13 at 07:19
  • 1
    @Annan: Java `File` objects are not opened, so don't need to be closed... See the answers to http://stackoverflow.com/q/4752266/43452 – Stobor Nov 20 '13 at 03:37
  • 3
    @Stobor if the previous content was larger than the new content, is the extra stuff deleted or will you find it at the end of the file after wrting in it less than that which should have been deleted. – Daren Jun 18 '15 at 11:49
  • 4
    if we don`t specify any value, it will be false and it will overwrite the old file – Mr.Q Jul 08 '17 at 05:13
  • 1
    Thanks for the tweaks @pmartin8 – Stobor Nov 08 '17 at 02:13
12

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

jnt30
  • 1,367
  • 2
  • 15
  • 21
5

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");
drfloob
  • 3,154
  • 1
  • 24
  • 31
  • I misread the question as the need to rewrite a file, e.g. modify the contents, not replace entirely with new content. – drfloob Jun 19 '09 at 04:23
  • 1
    Anyway, I was looking for overwriting a specific part of the file and this was the answer! – fyts Dec 08 '15 at 14:52
4

Since Java 7 and the new file API this is really simple using the java.nio.file.Files class:

Files.write(Path.of("foo.log"), "content".getBytes(StandardCharsets.UTF_8));

New in Java 8 to write list of UTF-8 string:

Files.write(Path.of("foo.log"), List.of("content line 1", "content line 2"));

New in Java 11 to write UTF-8 string:

Files.writeString(Path.of("foo.log"), "content");
Lii
  • 11,553
  • 8
  • 64
  • 88
2

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.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
1

In the below example, the "false" causes the file to be overwritten, true would cause the opposite.

File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close(); 
Sev
  • 15,401
  • 9
  • 56
  • 75
  • 3
    Curious! whats the benefit of introducing DataOutputSteam? – Adeel Ansari Jun 19 '09 at 04:16
  • The size() and writeUTF() methods have been useful to me thus far, so I chose to use that. You can also not convert to bytes before writing the string using DataOutputStream. – Sev Jun 19 '09 at 04:25
  • DataInputStream and DataOutputStream are specialized classes for working with a certain kind of binary file; they should not be used on text files. The correct way to read and write text files is with Readers and Writers: FileReader and FileWriter use the platform default encoding, while InputStreamReader and OutputStreamWriter let you specify the encoding (like UTF-8). – Alan Moore Jun 19 '09 at 12:44
1

There are times when one may want to keep a huge empty file so as to avoid extra cost of the OS allocating space on need basis. This is generally done by databases, Virtual machines and also in batch programs that process and write bulk data. This would improve the performance of the application significantly. In these cases, writing a new file and renaming it would not really help. Instead, the empty file will have to be filled up. That is when one must go for the override mode.

Lakshmi
  • 11
  • 2
0

Guava Files.write "Overwrites a file with the contents of a byte array":

Files.write(bytes, new File(path));
Vadzim
  • 24,954
  • 11
  • 143
  • 151