Search code examples
androidandroid-studiofileoutputstreamandroid-external-storage

Write data continuously to file in external storage - Android App


I am writing the data to the file in an external storage (SD card) on my android. The issue that I am facing is that it just makes one entry and does not go beyond that. I have looked up a number of Q/As here. Could someone please point me in the write direction? TIA!

FileOutputStream outputstream;
try {
    file1 = new File(Environment.getExternalStorageDirectory(), "MyData.txt");
    outputstream = new FileOutputStream(file1);
    OutputStreamWriter oswriter = new OutputStreamWriter(outputstream);
    BufferedWriter bwriter = new BufferedWriter (oswriter);
    bwriter.append(entry);
    bwriter.newLine();
    bwriter.close();
    outputstream.close();
} catch (Exception e) {
    e.printStackTrace();
}

Solution

  • You have to tell FileOutputStream to append the data. By default it just overwrites all contents there. For this you only need to use a different constructor FileOutputStream(File, boolean):

    outputstream = new FileOutputStream(file1, true);