如何使用 apache-commons-csv 在 .csv 文件中添加一列

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

我尝试向 csv 文件中添加一列。所以我得到了记录(这里 recordOut)并向列表中添加了一个元素。

代码

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);
}

错误

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

不允许向 headerRecord 列表中添加列?感谢您的帮助!

添加时不使用索引

改变

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

headerRecord.add("Value");