gpt4 book ai didi

java - 使用 openCSV 用新值更新一行

转载 作者:行者123 更新时间:2023-11-30 08:49:30 26 4
gpt4 key购买 nike

我需要使用 openCSV 实用程序用新值更新一行。例如,我有以下 CSV 文件,我需要将包含 TestdminUsername1TestdminUsername2 的行更新为 TestdminUsername1,Fail,Errors FoundTestdminUsername2,Fail,Errors Found 分别。

TestdminUsername1,Pass,No Error
TestAdminUsername2,Pass,No Error
TestAdminUsername3,Pass,No Error
TestAdminUsername4,Pass,No Error
TestAdminUsername5,Pass,No Error
TestAdminUsername6,Pass,No Error
TestAdminUsername7,Pass,No Error
TestAdminUsername8,Pass,No Error
TestAdminUsername9,Pass,No Error
TestAdminUsername10,Pass,No Error

下面是我正在使用的代码片段:

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

public class AppendToCSVExample
{
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception
{
String csv = "D:\\data2.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv, true));
String [] record1 = "TestdminUsername1,Pass,No Error".split(",");
String [] record2 = "TestAdminUsername2,Pass,No Error".split(",");
String [] record3 = "TestAdminUsername3,Pass,No Error".split(",");
String [] record4 = "TestAdminUsername4,Pass,No Error".split(",");
String [] record5 = "TestAdminUsername5,Pass,No Error".split(",");
String [] record6 = "TestAdminUsername6,Pass,No Error".split(",");
String [] record7 = "TestAdminUsername7,Pass,No Error".split(",");
String [] record8 = "TestAdminUsername8,Pass,No Error".split(",");
String [] record9 = "TestAdminUsername9,Pass,No Error".split(",");
String [] record10 = "TestAdminUsername10,Pass,No Error".split(",");

writer.writeNext(record1);
writer.writeNext(record2);
writer.writeNext(record3);
writer.writeNext(record4);
writer.writeNext(record5);
writer.writeNext(record6);
writer.writeNext(record7);
writer.writeNext(record8);
writer.writeNext(record9);
writer.writeNext(record10);

writer.close();

CSVReader reader = new CSVReader(new FileReader("D:\\data1.csv"), ',' , '"' , 1);

String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
//Verifying the read data here
System.out.println(Arrays.toString(nextLine));
String[] parts = Arrays.toString(nextLine).split(",");
if (parts[0].toString().contains("TestdminUsername1")) {
String [] recordTest = "TestdminUsername1, Fail, Errors found".split(",");
//Which method in openCSV needs to be used to update recordTest value in the File data2.csv
;
}
}
}
}
}

最佳答案

我个人建议您打开第二个 CSVWriter 到一个新文件 (data3.csv),当您从 data1 读取数据时,您写入 data3 以更改需要修改的数据。这样,如果您出于任何原因失败,您仍然拥有原始文件。最后,如果您只想要一个文件,可以删除 data1 并将 data3.csv 重命名为 data1.csv。

有一个问题,有人试图同时读取和写入同一个文件(Reading from a CSV file and writing to a new CSV file using openCSV in java),但我再次建议不要这样做,以防出现错误。

关于java - 使用 openCSV 用新值更新一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31380618/

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