Reputation: 97
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
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.
Modified Code: you have to give false value for append
parameter.
FileWriter fw = new FileWriter(file.getAbsoluteFile(),false);
Upvotes: 0
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
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