附加文件会导致覆盖(Java) [英] Appending file results in overwrite (Java)

查看:96
本文介绍了附加文件会导致覆盖(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在创建一个CSV文件,每次发生操作时,我都希望将数据写入该文件中.我遇到的问题是,它将在第二次进入时覆盖数据.如何将数据添加到文件末尾?

So I am creating a CSV file and everytime an action occurs I would like to write the data to the file. The problem I am having is that it will overwrite the data when entering the second time. How do I add the data to the end of the file?

 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(字符串名称,布尔值附加)以获取更多信息

This will open the file stored_hka in append mode instead of overwriting the contents. See the javadoc for FileOutputStream(String name, boolean append) for more information

这篇关于附加文件会导致覆盖(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆