2017-07-07 52 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

您可以在上面的代碼中執行所有操作。您不需要知道列的數量,只需使用','附加任何內容並打印即可。 –