gpt4 book ai didi

java - 追加文件导致覆盖(Java)

转载 作者:搜寻专家 更新时间:2023-11-01 01:06:48 25 4
gpt4 key购买 nike

所以我正在创建一个 CSV 文件,每次发生操作时,我都想将数据写入该文件。我遇到的问题是第二次输入时会覆盖数据。如何将数据添加到文件末尾?

 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;
}



}

最佳答案

而不是做

new FileOutputStream(stored_hka);

new FileOutputStream(stored_hka, true);

这将以附加模式打开文件 stored_hka 而不是覆盖内容。请参阅 FileOutputStream(String name, boolean append) 的 javadoc了解更多信息

关于java - 追加文件导致覆盖(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10000850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com