简体   繁体   中英

How to add a column in .csv file with apache-commons-csv

I try to add a column to a csv file. So I get the record (here recordOut ) and I add an element to the list.

Code

public <T> List<T> getListFromIterator(Iterator<T> iterator) { 
    Iterable<T> iterable = () -> iterator; 
    return StreamSupport .stream(iterable.spliterator(), false) .collect(Collectors.toList()); 
}

public void method() {
    // ... recordOut definition
    List<String> headerRecord = getListFromIterator(recordsOut.get(0).iterator());
    headerRecord.add(recordsOut.get(0).size() + 1, "Value");

    String filePath = file.getAbsolutePath();
    file.delete();

    CSVPrinter printer = new CSVPrinter(writer, Constants.CSV_FORMAT);
    printer.printRecords(recordsOut);
}

Error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 69, Size: 68

It is not allowed to add a column to the headerRecord list? Thank you for your help!

Don't use an index when adding

Change

headerRecord.add(recordsOut.get(0).size() + 1, "Value");

to

headerRecord.add("Value");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM