android FileNotFoundException(Is a Directory)解决办法

来源:互联网 发布:aws 阿里云 比较 编辑:程序博客网 时间:2024/06/02 05:44

        最近公司项目要求把从服务器读取的图片存到本地SD卡中,一开始以为很轻松啊,听着小曲,看着视频,敲着代码,这小资生活。。。。咳咳,扯远了,OK,代码敲完了,如下:

public void GetIamge(String urlPath){        HttpClient client = new DefaultHttpClient();        HttpGet get = new HttpGet(urlPath);        //String name = urlPath.substring(urlPath.lastIndexOf("."));        File dir = new File(Environment.getExternalStorageDirectory() + "/YunJian");        File file = new File(dir, "header.jpg");        if(!dir.exists()){            dir.mkdirs();        }        HttpResponse response = null;        try {            response = client.execute(get);            InputStream inputStream = response.getEntity().getContent();            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);            FileOutputStream outputStream = new FileOutputStream(file);            if(bitmap != null){                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);            }        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                    }

       一运行,报错:java.io.FileNotFoundException:XXX open falied: EISDIR(Is a directory)。傻眼了,不科学啊,怎么会把文件编译成文件夹呢。好吧,第一时间,发挥天才般的大脑。。。。。算了,还是找度娘吧,看了网上的方法,总结了一下:

  1. 可能是权限的问题,也就是没有加访问SD卡的权限;
  2. 可能是路径问题,有可能路径不存在导致的。
     按照这两种可能去找问题,发现不对路,没办法了,去官网,看一下File类,这才发现File类的构造函数中:File(File, String)构造函数创建的对象是文件夹,File(String, String)函数创建的对象才是文件,所以只需把上诉代码中的
File file = new File(dir, "header.jpg")
改为:
File file = new File(dir.getPath(), "header.jpg")
就可以了。
0 0
原创粉丝点击