2012-04-03 65 views
4

因此,我創建一個CSV文件,每次發生操作時我都想將數據寫入文件。我遇到的問題是,它會在第二次輸入時覆蓋數據。如何將數據添加到文件末尾?附加文件覆蓋結果(Java)

public boolean save_to_csv(){ 

    //check if directory exists, if not create the folder 
    File folder = new File(Environment.getExternalStorageDirectory() + "/HKA_CAL"); 
    //Environment.getExternalStorageDirectory() get the location of external storage 
    boolean success = true; 
    if(!folder.exists()) 
    { 
     success = folder.mkdir(); 
    }   
    if (success) 
    { 
     //success is true if folder has successfully been created 
     //now we can create/check if the file exists 

     File stored_hka = new File(Environment.getExternalStorageDirectory()+"/HKA_CAL/Stored_values.csv"); 
     boolean file_existed=true; 

     try{ 
      if(!stored_hka.exists()){ 
       stored_hka.createNewFile(); 
       file_existed=false; 
      } 
      FileOutputStream fOut = new FileOutputStream(stored_hka); 
      OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
      if(!file_existed){ 
       //if the file did not exist we need to write the titles of the csv 
       myOutWriter.append("Calibration Tracking\r\n"); 
       myOutWriter.append(",ZERO1,,Zero2,,cal1,,cal2,,CALIBRATION FACTORS\r\n"); 
       myOutWriter.append("Date,Stab,Read,Stab,Read,Stab,Read,Stab,Read,Unit S/N,F Zero,F Offset,F Factor\r\n"); 
      } 
      myOutWriter.append("Date" 
        +","+get_step3_stab()+","+get_step3_read() 
        +","+get_step6_stab()+","+get_step6_read() 
        +","+get_step8_stab()+","+get_step8_read() 
        +","+get_step11_stab()+","+get_step11_read() 
        +","+get_sn_num()+","+get_f_zero() 
        +","+get_f_offset()+","+get_f_factor()+"\r\n" 
        ); 
      myOutWriter.close(); 
      fOut.close(); 
     } 
     catch(Exception e){ 
      return false; 
     } 




     return true; 
    } 
    else 
    { 
     return false; 
    } 



} 

回答

8

而不是做

new FileOutputStream(stored_hka); 

new FileOutputStream(stored_hka, true); 

這將以附加模式打開文件stored_hka而不是覆蓋內容。見FileOutputStream(String name, boolean append)的Javadoc以獲取更多信息

+0

這似乎工作非常感謝 – yawnobleix 2012-04-03 20:39:33

+0

@yawnobleix它似乎'贊同Javadoc。 – EJP 2012-04-03 23:45:11

3

當你構建你的FileWriterFileOutputStream有一個構造函數的參數,它允許你把它放在附加模式:

new FileOutputStream("/path/to/file", true) 
2

變化

FileOutputStream fOut = new FileOutputStream(stored_hka); 

FileOutputStream fOut = new FileOutputStream(stored_hka, true); 
1
FileInputStream("valid path of file", true); 

它會打開一個文件的布爾在追加模式下。布爾值是用於是否要以追加模式打開文件。