Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencsv + add new column to existing csv

Tags:

java

opencsv

It there any possibility to add a new column to existing csv file, means

existing file

userid,name
1,Jim
2,Sally
3,Bob

modified output file

userid,name,time
1,Jim,64913824823208
2,Sally,64913824900056
3,Bob,64913824966956

Thanks in advance

like image 809
Suganthan Madhavan Pillai Avatar asked Sep 30 '22 14:09

Suganthan Madhavan Pillai


1 Answers

You mean something like this?

CSVReader reader = new CSVReader(new FileReader("input.csv"));
CSVWriter writer = new CSVWriter(new FileWriter("output.csv"), ',');
String[] entries = null;
while ((entries = reader.readNext()) != null) {
    ArrayList list = new ArrayList(Arrays.asList(entries));
    list.add(xxx); // Add the new element here
    writer.writeNext(list);
}
writer.close();

Haven't tried to compile it but something like this should work. There are many options to use OpenCsv (e.g., you can link the data to beans directly), but this is the shorter solution.

like image 178
rlegendi Avatar answered Oct 09 '22 04:10

rlegendi