user3606198
user3606198

Reputation: 97

BufferedWriter cannot restart

I am using the java bufferedwriter to write to a csv file. Everytime I run the program, the data is being written correctly to the file but the data from previous runs are still found in the file.

I need the file to be empty each time before the bufferwriter starts again.

I tried using the flush() method already.

Anyone has some suggestions? The following is my code;

if (!file.exists()) {
file.createNewFile();
                }

FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.append(" " + epochs);
bw.append(",");
bw.append("badfact" + badfacts);
bw.flush();
bw.close();
}

Upvotes: 0

Views: 182

Answers (3)

atish shimpi
atish shimpi

Reputation: 5023

FileWriter(String fileName, boolean append)

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

Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.

refer java docs

Modified Code: you have to give false value for append parameter.

FileWriter fw = new FileWriter(file.getAbsoluteFile(),false);

Upvotes: 0

gprathour
gprathour

Reputation: 15333

You need to do the following,

FileWriter fw = new FileWriter(file.getAbsoluteFile(), false);

The second parameter in FileWriter constructor is for appending.

If it is true then data will be appended to the previous data in the file. If false then the previous data will be removed and new data will be written.

Upvotes: 2

Eypros
Eypros

Reputation: 5723

As @GPRathour answered the second parameter is for appending to file.

FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);

I just wanted to add that the 1 argument call is equivalent to append = false so you can use this also.

FileWriter fw = new FileWriter(file.getAbsoluteFile());

Upvotes: 2

Related Questions