使用openCSV使用新值更新行

时间:2015-07-13 10:13:07

标签: java opencsv

我需要使用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
             ;
         }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:2)

我个人建议你打开第二个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),但如果出现错误,我会再次提出建议。