简体   繁体   English

如何在文本文件中添加一行而不覆盖它(JAVA)?

[英]How to add a line in a text file without overwriting it (JAVA)?

My data is stored in an ArrayList whose size increases during program execution. 我的数据存储在一个ArrayList中,其大小在程序执行期间会增加。 I managed to save all the data whenever the size increases, but this brings me to overwrite the data already stored. 每当大小增加时,我都设法保存了所有数据,但这使我覆盖了已存储的数据。 The solution is to go directly to the bottom line and insert the contents of the last cell of ArrayList. 解决方案是直接转到最底行,然后插入ArrayList的最后一个单元格的内容。 Unfortunately I do not know how to implement it. 不幸的是,我不知道如何实现它。 Thank you for helping me to do this. 谢谢您的帮助。

Below is the method I used. 下面是我使用的方法。

private void SaveLocationData(){
    try {

        FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_PRIVATE);
        DataOutputStream dout = new DataOutputStream(output);                     
        dout.writeInt(LocationList.size()); 
        for (Location location : LocationList) {
            dout.writeUTF(location.getLatitude() + "," + location.getLongitude());              
        }
        dout.flush(); // Flush stream ...
        dout.close(); // ... and close.
    } catch (IOException exc) {
        exc.printStackTrace();
    }   
}

Use MODE_APPEND : 使用MODE_APPEND

 FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_APPEND);

From the doc : 文档

File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it. 文件创建模式:与openFileOutput(String,int)一起使用,如果文件已经存在,则将数据写入现有文件的末尾而不是擦除它。

You can try this too 你也可以尝试

        FileWriter fstream = new FileWriter("x.txt",true); //this will allow to append
        BufferedWriter fbw = new BufferedWriter(fstream);
        fbw.write("append txt...");
        fbw.newLine();
        fbw.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM