2017-07-07 54 views
0

我想运行下面的代码与Apache的公共,为了把它写入到CSV文件。 finalResult数组的打印语句显示它具有我想要填充的内容。由于某种原因,它不会将数据发送到指定的csv。数据没有被写入到csv与Apache Commons

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()); 
    } 
+0

您使用不带'catch'或'finally'或资源声明的传统'try',这就是为什么不能编译!此外,在wirter使用它们之后,最好关闭潜在的作者,因为你不知道他们是否使用缓冲...... – fabian

+0

你可以将finalResult的内容添加到问题中。当你执行你看到的两个打印输出结果时你也看到了什么? – digidude

+0

为什么你有两个'FileWriter's?看来你只能写信给其中一个人 - 这不是带有'csv'后缀的人吗? – Itai

回答

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,但这是另一个问题。

+0

复杂代码的原因是因为它需要根据用户输入处理未知数量的列。然后,我希望它写入一个csv,并在每次索引达到列标题数组的大小时创建一个新行,以便格式化得很整齐。我只是简化了代码以更快地获得主要问题解决方案 – dgelinas21

+0

您可以在上面的代码中执行所有操作。您不需要知道列的数量,只需使用','附加任何内容并打印即可。 –