Safouan Ben Jha
Safouan Ben Jha

Reputation: 21

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. 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. 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();
    }   
}

Upvotes: 1

Views: 1381

Answers (2)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

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();

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157437

Use 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.

Upvotes: 2

Related Questions