如何使用apache commons将新列添加到csv文件中

问题描述 投票:3回答:1

我有一个看起来像这样的csv文件

name,age,total
xyz,22
abc,20

处理完csv文件后应如下所示

name,age,total
xyz,22,100
abc,20,102

运行此代码后

public class Converter {

    public static void main(String[] args) throws IOException {

        BufferedWriter writer = Files.newBufferedWriter(Paths.get(Constants.SAMPLE_CSV_FILE));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);

        csvPrinter.print(100);
        csvPrinter.print(102);

        csvPrinter.close();
    }

}

输出csv文件变成这样

100
102

我希望100和102总计不足。怎么做

java csv append apache-commons writing
1个回答
-1
投票

首先,您不应该覆盖现有文件。因此,在FileWriter构造函数上使用appending参数:

FileWriter pw = new FileWriter("C:\\exampleFile.csv",true); 

其次,正如您在结果中看到的那样,CSVPrinter按行遍历您的文件。如果要添加新列,实际上需要迭代每一行并在每次迭代时插入新列的行数据,如详细解释here

© www.soinside.com 2019 - 2024. All rights reserved.