追加到Java中的CSV文件的最后一行

问题描述:

下面的代码是我目前拥有的代码,但它覆盖了当时csv文件中的所有数据,而不是将其追加到最后。是否有捷径可寻?追加到Java中的CSV文件的最后一行

public void printCustomerList() throws IOException{ 
     FileWriter pw = new FileWriter("F:\\data.csv"); 
     Iterator s = customerIterator(); 
     if (s.hasNext()==false){ 
      System.out.println("Empty"); 
     } 
     while(s.hasNext()){ 
      Customer current = (Customer) s.next(); 
      System.out.println(current.toString()+"\n"); 
      pw.append(current.getName()); 
      pw.append(","); 
      pw.append(current.getAddress()); 
      pw.append("\n"); 
     } 
      pw.flush(); 
      pw.close(); 
    } 
+1

http://*.com/questions/6027764/how-to-append-data-to-a-file的可能重复。 –

尝试打开文件中像这样

FileWriter pw = new FileWriter("F:\\data.csv",true); 

true参数进行追加。

+0

谢谢。它有帮助。 –

使用FileWriter pw = new FileWriter("F:\\data.csv", true);

参考:FileWriter

您需要使用不同的构造函数为您FileWriter

FileWriter pw = new FileWriter("F:\\data.csv", true); 

欲了解更多信息,请参阅JDK API for this constructor