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

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *