Search code examples
javaopencsv

Opencsv + add new column to existing csv


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


Solution

  • 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.