更新CSV文件中的特定行

时间:2017-08-04 11:55:20

标签: java csv

我想更新.CSV文件中的特定行(满足预定义条件)。

这是我的代码:

ProductID,ProductName,price,availability,type
12345,abc,300,yes,medicine
23456,def,400,yes,testing
34567,ghi,200,no,medicine
45678,jkl,500,no,testing

这是代码

    CsvReader products = new CsvReader("D:\\sample.csv");
            CsvWriter csvOutput = new CsvWriter(new FileWriter("D:\\sample.csv", true), ',');
            products.readHeaders();
            products.getRawRecord();
            while (products.readRecord())
            {
                String productID = products.get("ProductID");
                String productName = products.get("ProductName");
                String supplierID = products.get("price");
                String categoryID = products.get("availability");
                String quantityPerUnit = products.get("type");

                if(productID.equals("roche123")){
                    csvOutput.replace(productName, "12", "newproductName");
                    csvOutput.replace(supplierID , "12", "newsupplierID ");
                }

但它不起作用。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

方法CsvWriter.replace不是实例方法,也不是当前记录的内联替换。

相反,它应该用作

String replace = CsvWriter.replace(
    inputString, // somefoobar
    substringToReplace, // foobar
    substringSubstitute); // candy
// replace will be "somecandy"

以下代码段应说明原则。

假设sample_in.csv

ProductID,ProductName,price,availability,type
12345,abc,300,yes,medicine
23456,def,400,yes,testing
34567,ghi,200,no,medicine
45678,jkl,500,no,testing
roche123,product 12,supplier 12,no,foobar

代码段

CsvReader products = new CsvReader("sample_in.csv");
CsvWriter csvOutput = new CsvWriter(new FileWriter("sample_out.csv", true), ',');
products.readHeaders();

csvOutput.writeRecord(products.getHeaders());

String[] outValues = new String[5];
while (products.readRecord()) {
    String productID = products.get("ProductID");
    String productName = products.get("ProductName");
    String supplierID = products.get("price"); // is this correct?
    String categoryID = products.get("availability");
    String quantityPerUnit = products.get("type");

    if (productID.equals("roche123")) {
        productName = CsvWriter.replace(productName, "12", "newproductName");
        supplierID = CsvWriter.replace(supplierID, "12", "newsupplierID");
    }

    outValues[0] = productID;
    outValues[1] = productName;
    outValues[2] = supplierID;
    outValues[3] = categoryID;
    outValues[4] = quantityPerUnit;
    csvOutput.writeRecord(outValues);
}

将生成sample_out.csv

ProductID,ProductName,price,availability,type
12345,abc,300,yes,medicine
23456,def,400,yes,testing
34567,ghi,200,no,medicine
45678,jkl,500,no,testing
roche123,product newproductName,supplier newsupplierID,no,foobar

来自输入行

roche123,product 12,supplier 12,no,foobar
  • ProductName已从product 12更新为product newproductName
  • price已从supplier 12更新为supplier newsupplierID

修改该代码段正在使用JavaCSV库。