How to create a text file on Android?

1

I've looked for several examples and scripts on the internet and even here in stackoverflow but I still can not create a text file in android, the last code I tried to use was unsuccessful:

How to create a txt file?

I simply compiled and such, but did not generate the file, my Manifest already has the necessary permissions.

    
asked by anonymous 12.09.2016 / 18:32

1 answer

1

You need to check the permission:

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

Here is an example that saves a text file on the 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 it, like this:

generateNoteOnSD(this, "nome_do_arquivo", "texto_do_arquivo");
    
12.09.2016 / 19:04