1. 程式人生 > >android FileNotFoundException(Is a Directory)解決辦法

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")
就可以了。