Martin Erlic
Martin Erlic

Reputation: 5667

How to empty FileWriter output before appending new data?

When ever I run the program again it simply appends to the existing file.

I want to empty the file and then start with the business logic

FileWriter empty = new FileWriter("output.csv", true); //true = append
empty.write("");
empty.close();

FileWriter outfile = new FileWriter("output.csv", true); //true = append
// Add desired content
outfile.flush();
outfile.close();

Upvotes: 0

Views: 1681

Answers (3)

GhostCat
GhostCat

Reputation: 140427

Thing is:

FileWriter outfile = new FileWriter("output.csv", true); //true = append

creates a FileWriter that appends to an existing file.

FileWriter outfile = new FileWriter("output.csv", false);

creates a FileWriter that will overwrite any content that is currently in that file.

Those are the two options you have!

But the real answer here: read the javadoc of the classes you are using, this behavior is explicitly documented.

And just for the record: this is one of the reasons why one should be really careful about using booleans parameters as "flags". I agree; for a newbie, having that "true" sitting there doesn't say anything.

A "better" interface could be used like:

FileWriter empty = new FileWriter("output.csv", FileWriterMode.APPEND);

And as your requirements seems to be: you want to blank that output file; and then write data to it ... simply forget about appending. In essence, you are asking: how do I overwrite my CSV file with new content. And then the answer is - you do not need that "empty" writer; just go with:

FileWriter outfile = new FileWriter("output.csv", false);

By doing so; you always overwrite what is currently in the output file; then you add content.

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

To make it empty, you can overwrite it and you need to use a single file.
The empty FileWriter is not required.

Specify the append parameter to false in the public FileWriter(File file, boolean append) constructor call or better don't specify it by using the public FileWriter(String fileName) constructor.
By default it overwrites the file :

FileWriter outfile = new FileWriter("output.csv"); 

Upvotes: 1

but you are constructing the object to do so: FileWriter("output.csv", true)

the doc explains what the boolean value do in the file:

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

set that boolean parameter to false in order to overwrite the file...

FileWriter("output.csv", false)

or simple:

FileWriter("output.csv")

Upvotes: 2

Related Questions