Lazy Ninja Lazy Ninja - 1 year ago 206
Android Question open failed eacces (permission denied) on device

The following code which consists of downloading a file from a server and save it in the storage works fine when the device has an internal storage.

But when I tried it with a device with no internal storage, only with external storage I get the following exception. open failed eacces (permission denied)

public void downloadFile(String dlUrl, String dlName) {
int count;

HttpURLConnection con = null;
InputStream is = null;
FileOutputStream fos = null;

try {
URL url = new URL( dlUrl );
con = (HttpURLConnection) url.openConnection();

is = url.openStream();
String dir = Environment.getExternalStorageDirectory() + Util.DL_DIRECTORY;
File file = new File( dir );
if( !file.exists() ){

Util.LOG_W(TAG, "Downloading: " + dlName + " ...");

fos = new FileOutputStream(file + "/" + dlName);
byte data[] = new byte[1024];

while( (count = != -1 ){
fos.write(data, 0, count);

Util.LOG_D(TAG, dlName + " Download Complete!");

} catch (Exception e) {
Util.LOG_E(TAG, "DOWNLOAD ERROR = " + e.toString() );
bServiceDownloading = false;
try {
if( is != null)
if( fos != null)
if( con != null)
} catch (Exception e) {
Util.LOG_E(TAG, "CLOSE ERROR = " + e.toString() );

And in manifest file I has the following:

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

I have tried a lots of suggestions in StackOverflow so far, nothing seems to work.

Any suggestions what maybe the cause?
By the way Environment.getExternalStorageDirectory() returns /mnt/sdcard/ and file.mkdir() return false.

Answer Source

This problem seems to be caused by several factors.
First add this permission in your manifest file and check if it is working:

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



If first step is not working, try this step:

 String dir = Environment.getExternalStorageDirectory().getAbsolutePath()

For me the following worked:
The problem is that getExternalStorageDirectory returns /mnt/sdcard whereas I need the actual path of external storage which is /mnt/sdcard-ext and there is no API in android that can get me the absolute path of removable sdcard.
My solution was to hard code the directory as follows:

String dir = "/mnt/sdcard-ext" ;

Since the application is intended to work only on one device, the above did the job.
If you encounter the same problem, use an file explorer application to find out the name of the external directory and hard code it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download