2

我有一个包含使用Apache Common CSV library 1.5生成 CSV 文件的方法的类

public class CSVGenerator {

    private static final String CSV_FILE = "./credentials.csv";
    private static CSVPrinter csvPrinter;

    public static void generateCSV(String FirstName, String LastName, String DOB) {


        try {
            BufferedWriter writer = Files.newBufferedWriter(Paths.get(CSV_FILE) );

            csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader("FirstName", "LastName", "DOB"));

            csvPrinter.printRecord(FirstName, LastName, DOB);
            csvPrinter.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我的主类中有一个方法,该方法将调用该方法generateCSV()几次。
如何编写新行并将其附加到现有的 CSV 文件?使用我当前的实现,它将继续覆盖我的第一行。

更直接的解决方案是在任何 Java 集合(数组或列表)中收集我的所有数据,然后在最后迭代集合并将其一次性写入 CSV。但我不会那样做。我更喜欢在 CSV 中写入一行,然后执行其他操作,然后再次调用该方法以写入新行并将其附加到现有的 CSV 中。

谢谢。

4

3 回答 3

7

使用APPEND选项:

BufferedWriter writer = Files.newBufferedWriter(
        Paths.get(CSV_FILE), 
        StandardOpenOption.APPEND, 
        StandardOpenOption.CREATE);

您必须进行设置,以便满足以下条件之一

  1. 在开始之前,请确保输出文件为空或不存在;或者
  2. APPEND仅在第二次和后续调用时使用该选项generateCSV

顺便说一句,您在每次调用时都创建一个新的BufferedWriterand ,而不是关闭任何一个。这很浪费,您可能应该在构造函数中创建它们,实现,并实现一个方法来清理。然后将调用代码包装在实例化的 try-with-resources 中。CSVPrintergenerateCSVCloseableclose()generateCSV

于 2019-05-08T06:14:22.610 回答
1

这是一种更简单的方法。在检查文件是否存在之后,您应该实例化 Writer 对象,否则将创建实例化文件,并且每次您都会将 file.exists() 设为 true。如果文件存在,则需要使用 withSkipHeaderRecord() 创建 CSVPrinter,否则使用 header() 方法的任何实现。FileWriter 构造函数采用带有 File 参数的可附加参数。如果文件在那里,您必须将可附加参数设置为 true。

File file = new File(filePath.concat("/").concat(fileName));
        if(file.exists()) {
            fileWriter = new FileWriter(file, true);
            csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withSkipHeaderRecord());
        }
        else {
            fileWriter = new FileWriter(file);
            csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader("FirstName", "LastName", "DOB"));
            
        }
于 2021-09-18T14:08:54.227 回答
0

检查https://stackoverflow.com/a/56034569/3602015中告知的条件后的解决方案

    String data = "stackoverflow";
    File file = new File("tmp/sample.csv");
    BufferedWriter writer;
    CSVPrinter csvPrinter;
    if (!file.exists()) {
        writer = Files.newBufferedWriter(Paths.get("tmp/sample.csv"));
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("S No","Col1"));
    } else {
        writer = Files.newBufferedWriter(Paths.get("tmp/sample.csv", StandardOpenOption.APPEND
                , StandardOpenOption.CREATE);
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
    }

    csvPrinter.printRecord("1", data);
    csvPrinter.flush();
于 2021-06-16T13:22:23.840 回答