Reputation: 909
Im using CSVWriter(OpenCSV)
to write the data into CSV
in Java
.
Can any one please help me to append data to the existing data?
I tried opening the file as given below
FileWriter pw = new FileWriter("F:\\data.csv",true);
But I could able to see the Old content is replaced and only the new data is available in the file? I want the old data along with new data.
Upvotes: 0
Views: 28290
Reputation: 139
I was using :
CSVWriter csvWriter = new CSVWriter(Files.newBufferedWriter(Paths.get(csvOutput))); When I used:
CSVWriter csvWriter = new CSVWriter(new FileWriter(csvOutput, true));
IT Worked !
Upvotes: 0
Reputation: 2271
If you are using openCSV, then do something like this :-
CSVWriter writer = new CSVWriter(new FileWriter(csv, true));
here is full example:-
import java.io.FileWriter;
import au.com.bytecode.opencsv.CSVWriter;
public class AppendToCSVExample
{
public static void main(String[] args) throws Exception
{
String csv = "data.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv, true));
String [] record = "3,David,Feezor,USA,40".split(",");
writer.writeNext(record);
writer.close();
}
}
To append new record on existing .csv file, you have to enable append mechanism of FileWritter class(here 'true' - second argument) which enables append feature of FileWritter class.
Hope this may work for you.
Upvotes: 4