Search code examples
javaandroidfilereaderreadfile

Add Text To An Existing Text File


Hello I am new to Android development. I am developing an app as a training. So now my target is to add some new text to an existing text file.

For example: I have a text file in "sdCard/android.txt" and in this file there are some data written "I love android". Now I want to add some more texts "It is awesome" in a new line of that file.

Finally the android.txt ahould look like this:

I love android
It is awesome

So how can I achieve that?


Solution

  • You can just do it as you do it in Java.

    try {
        String fn = getExternalFilesDir(null) + File.separator + "android.txt";
        BufferedWriter bw = new BufferedWriter(new FileWriter(fn, true));
        bw.write("\nIt is awesome\n");
        bw.close();
    
        // checking
        BufferedReader br = new BufferedReader(new FileReader(fn));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }