FileOutputStream crashes with “open failed: EISDIR (Is a directory)” error when downloading image

Deadly 提交于 2019-11-28 06:49:16

3.png is a directory, because you make it so by calling f.mkdirs();. Try f.getParentFile().mkdirs() instead. From the documentation:

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

(emphasis mine). In other words, the entire path contained in the File instance f is taken to be a directory name, up to and including the final part (3.png in the example output).

The problem is that you are using the function

f.mkdirs();

this function will create a folder called "3.png" instead of a file called "3.png", so delete this folder first,

then replace the function

f.mkdirs();

to

f.createNewFile();

Hope this help.

replace f.mkdirs() with f.createNewFile().

You can first make the directory and then further write the code.

 URL downloadURL=null;
    HttpURLConnection urlConnection=null;
    InputStream inputStream=null;
    FileOutputStream fos=null;
    Uri uri=Uri.parse(url);
    try {
        downloadURL=new URL(url);
        urlConnection= (HttpURLConnection) downloadURL.openConnection();
        inputStream=urlConnection.getInputStream();
        File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/");
        if(!file.exists())
        {
            file.mkdirs();
        }
        File file1=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/"+uri.getLastPathSegment());
        fos=new FileOutputStream(file1);
        byte[] buffer=new byte[1024];

        int read=-1;
        while((read=inputStream.read(buffer))!=-1)
        {
           /* Message.L(""+read);*/
            fos.write(buffer,0,read);
        }

    }

Like this you can do

File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/");
        if(!file.exists())
        {
            file.mkdirs();
        }
        File file1=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/"+uri.getLastPathSegment());
        fos=new FileOutputStream(file1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!