How to create a text file on Android?

Asked

Viewed 1,802 times

2

I’ve looked for several examples and scripts on the internet and even here in stackoverflow but still could not create a text file on android, the last code I tried unsuccessfully was this:

How to create a txt file?

Simply compiling and such, but not generating the file, my Manifest already has the necessary permissions.

1 answer

1

You need to check the permission:

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

Below is an example that saves text file on device.

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

Just call him that way:

generateNoteOnSD(this, "nome_do_arquivo", "texto_do_arquivo");
  • What I need to change in this code to save in the internal memory of the mobile? my mobile has no SD card.

  • https://developer.android.com/training/basics/data-storage/files.html This link can help you, explain internal and external storage.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.