Skip to content Skip to sidebar Skip to footer

Saving A Text File To Public Internal Memory Location In Android

I am writing an App, in which I would like to append a text file, as various user actions happen. I would like the text file to be located in internal memory. I would like the te

Solution 1:

Ok, I have this working as I want it to, now. It will save the text file (and append it each time it is written) to the non-removable DOWNLOAD folder of a tablet/phone. My target was a minimum SDKversion of 16 (4.1.2 Jellybean).

I will post the code below, for anyone else who gets confused by this issue.

try {
File path = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "mytextfile.txt");
FileOutputStream fOut = new FileOutputStream(myFile,true);
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
    myOutWriter.append("the text I want added to the file");
    myOutWriter.close();
    fOut.close();

    Toast.makeText(this,"Text file Saved !",Toast.LENGTH_LONG).show();
    }

    catch (java.io.IOException e) {

    //do something if an IOException occurs.
    Toast.makeText(this,"ERROR - Text could't be
    added",Toast.LENGTH_LONG).show();
                      }

You will also need the following line added to the Manifest:

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

You will need to import:

import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.File;

Solution 2:

I would like the text file to be located in internal memory.

"Internal memory" does not have a lot of meaning from a programming standpoint.

I would like the text file to also be visible under Windows Explorer, if the user connects the tablet with a usb cable.

That would be external storage.

but I can not seem to make the file visible in File Manager.

Use MediaScannerConnection and its scanFile() method to tell the MediaStore about the file. That will at least allow the file to be visible to an MTP client like Windows' explorer windows. Note that you may need to "refresh" or "reload" in that explorer window to get Windows to pick up the new file.

Post a Comment for "Saving A Text File To Public Internal Memory Location In Android"