2017-04-25 122 views
1
FileWriter outfile = new FileWriter("ouput.csv", true); //true = append 

     for(int len = 0; len < tempList.size(); len++) { 
      LineItem tempItem = tempList.get(len); 
      if (len == 0) { 
       lastTime = tempItem.getTimeEnd(); 
       tempItem.setStatus("OK"); 
       //out 
       output(tempItem.toCSV(), outfile); 
      } else { 
       if (tempItem.getTimeStart().compareTo(lastTime) <= 0) { 
        //WARN 
        if (!tempItem.getStatus().equals("OVERLAP")) { 
         tempItem.setStatus("WARN"); 
        } 

       } else { 
        //OK 
        //System.out.println("OK ;" + tempItem.toCSV()); 
        if (!tempItem.getStatus().equals("OVERLAP")) { 
         tempItem.setStatus("OK"); 
        } 
       } 
       // file out write 
       output(tempItem.toCSV(), outfile); 

       lastTime = tempItem.getTimeEnd(); 

      } 

     } 
    } 

    private static void output(String line, FileWriter outfile) throws IOException { 
     System.out.println(line); 

     // Write each line to a new csv file 
     outfile.write(line + "\n"); 

    } 

爲什麼我的output.csv文件爲0 kb且爲空?但是,當我打印到行,我看到我的控制檯中的每個字符串...FileWriter輸出爲csv文件爲空

+0

考慮在FileWriter上調用'flush()'和'close()'。 – Berger

回答

0

output(tempItem.toCSV(), outfile);請添加以下語句。你忘了flushClose自動flush爲你。

outfile.close(); 
2

您未關閉FileWriter

注意刷新以及關閉的建議是多餘的。

0

當你flush(outfile)它將被寫入文件。如果你close(outfile)它會被自動刷新。有時你想在其他時間flush(),但往往沒有必要。你應該完成總是關閉文件。

由於Java 7,它往往是一個好主意,用嘗試 - 與資源:

try(FileWriter outfile = new FileWriter("output.csv", true)) { 
    // code that writes to outfile 
} 

因爲FileWriter工具Closeable,它會自動調用outfile.close()在執行離開該塊。