0

I am creating a sample application in my android phone to create a new text file and write some data on to that text file.

Gaurav K
  • 101
  • 1
  • 2
  • 4

1 Answers1

9

Use these code you can write a text file in SDCard along with you need to set permission in android manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

for device having os >= LOLIPOP you need to ask permissions runtime, this is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Lalit Dhameliya
  • 348
  • 3
  • 8