-1

I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)

Example of my code (I tried more variations):

try {
    File dir = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(dir, "output.txt");
    if (!file.exists()) {    
        file.createNewFile();
    } 
    FileOutputStream stream = new FileOutputStream(file);
    stream.write(("some text").getBytes());
    stream.close();
    toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
    toast.show();
} catch (Exception e) {
    toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
    //toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
    toast.show();
}
ColdFire
  • 6,764
  • 6
  • 35
  • 51
Jala38
  • 1
  • 1

2 Answers2

1

You have to set the

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

permission in your AndroidManifest.xml file.

If you run your app on Android 6.0 or higher you have to request this permission at runtime.

Request App Permissions

csabapap
  • 1,031
  • 1
  • 9
  • 14
0

I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.

Jala38
  • 1
  • 1