Apache Commons

时间:2017-07-07 14:19:48

标签: java csv javafx apache-commons

我正在尝试使用apache commons运行以下代码,以便将其写入csv文件。 finalResult数组的print语句显示它包含我想要填充的内容。由于某种原因,它不会将数据发送到指定的csv。

public void handle(ActionEvent runButton) {
    String csvFile = (userHomeFolder + "/" + fileName.getText() + ".csv");
    FileWriter writer = new FileWriter(csvFile);
    try {

        final Object [] FILE_HEADER = columnHeaders.toArray();
        int modval = 2;
        final String NEW_LINE_SEPARATOR = "\n";
        FileWriter fileWriter;
        CSVPrinter csvFilePrinter;
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        List rowResult = new ArrayList();

        fileWriter = new FileWriter(fileName.getText());
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        try {

            //CREATE CSV FILE HEADER
            System.out.println("File header: " + FILE_HEADER);
            csvFilePrinter.printRecord(FILE_HEADER);

            for(int y = 0; y < finalResult.size(); y++) {

                if(y % modval == 0) {
                    rowResult.add(finalResult.get(y));
                    csvFilePrinter.printRecord(rowResult);
                    System.out.println(rowResult);
                    rowResult.clear();
                }else {
                    //this means it is not the last value in the row
                    rowResult.add(finalResult.get(y));
                    System.out.println("fr: " + finalResult.get(y));
                }

            }

        } catch (Exception e) {
            System.out.println("Error in csvFileWriter");
            e.printStackTrace();

        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e ) {
                System.out.println("Error while flushing/closing");
            }
        }
    }
}
    //below catches any errors for any of the above work
    catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
   }

1 个答案:

答案 0 :(得分:1)

为什么你需要几十行代码和一个第三方库来完成printf可能在5行中完成的工作?创建PrintWriter并使用printf进行书写。完成。

try (PrintWriter pw = new PrintWriter(csvFile)) {
    pw.printf("%s\n", FILE_HEADER);

    for(int i = 0; i < finalResult.size(); i+=2) { // no need to modulo
        pw.printf("%s\n", finalResult.get(i)); // no idea what type finalResult.get(i) is, format it if you need to
    }
}

您不应该通过对文件分隔符csvFile进行硬编码来创建/,但这是另一个问题。