gpt4 book ai didi

java - 更新 CSV 文件中的特定行

转载 作者:行者123 更新时间:2023-11-30 06:34:04 25 4
gpt4 key购买 nike

我想更新 .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 ");
}

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

最佳答案

方法 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
  • ProductNameproduct 12 更新为 product newproductName
  • price 列从 supplier 12 更新为 supplier newsupplierID

编辑该代码段正在使用 JavaCSV 库。

关于java - 更新 CSV 文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com