2012-04-03 62 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); 

它会打开一个文件的布尔在追加模式下。布尔值是用于是否要以追加模式打开文件。