我需要使用openCSV实用程序用新值更新一行。例如,我有以下CSV文件,我需要将包含TestdminUsername1
和TestdminUsername2
的行分别更新为TestdminUsername1,Fail,Errors Found
和TestdminUsername2,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。
之前有一个问题,有人试图同时读取和写入同一个文件(从CSV文件中读取并使用java中的openCSV写入新的CSV文件),但我再次建议不要这样做,以防出现错误。