0

In my app I am trying to create a file and write to it.
This is my code:

try {
    File tmpDir = new File("/sdcard/LivingstoneTemp/");
    tmpDir.mkdirs();
    String filename = "Livingstone_" +UUID.randomUUID() + ".html";
    File outputFile = new File(tmpDir, filename);

    FileOutputStream fos = new FileOutputStream(outputFile);

    byte[] data = response.getBytes();
    fos.write(data);
    fos.flush();
    fos.close();
} catch (Exception e) {
    Log.i("LivingstoneInfo", "Error: " + e.getMessage());
}

Permissions:

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

I get a "No such file or directory" exception.

I'm running this on a Nexus 5 with an internal storage.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Johann
  • 27,536
  • 39
  • 165
  • 279
  • 10
    "I'm running this on a Nexus 5 with an internal SD card" -- no, you are running this on a Nexus 5 with [external storage](https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html). Beyond that, **NEVER HARDCODE PATHS**. Use methods on `Context` (e.g., `getExternalFilesDir()`) or `Environment` (e.g., `getExternalStoragePublicDir()`) to get at root directories. And, on Android 6.0, those permissions are `dangerous`: https://stackoverflow.com/questions/32635704/cant-get-the-permission – CommonsWare Nov 12 '15 at 15:48
  • 1
    What I meant by "internal storage" is that it's not an external SD card. The hardcoded path is just temporarily for debugging purposes. – Johann Nov 12 '15 at 15:51
  • what OS version is on Nexus? – Viktor Yakunin Nov 12 '15 at 16:05
  • @CommonsWare You're answer was only partially helpful. You didn't address my issue directly as to why I could not write to the file. It turns out that, yes, I am using Android 6.0 and even with permissions added, they are not enabled. I had to manually enable them under Settings. I am surprised that Android 6.0 didn't ask me to confirm the permission at the moment I needed it. This is probably because my target SDK is 16 and by default does not prompt the user when running on Android 6.0 – Johann Nov 12 '15 at 16:09
  • Also worth noting to those who encounter this issue. If you delete your cache under Settings, the permissions revert to being disabled. – Johann Nov 12 '15 at 16:30
  • 1
    @AndroidDev You have to ask the user for permission at runtime. The OS will not do so for you. – phxhawke Nov 12 '15 at 16:36

0 Answers0