android FileNotFoundException(Is a Directory)解决办法

        最近公司项目要求把从服务器读取的图片存到本地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")
就可以了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值