-1

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?

Bentaye
  • 9,403
  • 5
  • 32
  • 45
  • Possible duplicate of [How To Read/Write String From A File In Android](https://stackoverflow.com/questions/14376807/how-to-read-write-string-from-a-file-in-android) – Bentaye Feb 28 '18 at 16:06

2 Answers2

0

You can look at this example and use a BufferedWriter. When you execute File-Read or -Write operations, make sure to always use try/catch blocks.

public void appendText () {
  BufferedWriter bw = null;
  try {
     bw = new BufferedWriter(new FileWriter("Path-to-your-file", true));
     bw.write("text-to-append");
     bw.newLine();
     bw.flush();
  } catch (IOException ioe) {
     ioe.printStackTrace();
  }
}

You should definitely read about IO (Input-Output) Operations in Android/Java. https://docs.oracle.com/javase/tutorial/essential/io/ Good luck!

Bentaye
  • 9,403
  • 5
  • 32
  • 45
Vr33ni
  • 101
  • 16
0

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();
}
ghchoi
  • 4,812
  • 4
  • 30
  • 53
  • Suppose I have 3 lines in that text files. Now if I want to retrieve that 3 line in 3 string variable then how can I do that? And how can I know how much lines are in total in the file? – user9424533 Feb 28 '18 at 16:52
  • Yeah that's right. But when the number of line will be unknown then? – user9424533 Feb 28 '18 at 17:03
  • Then you can use `while` loop and `List` if you need to store lines. – ghchoi Feb 28 '18 at 17:06