android FileNotFoundException(Is a Directory)解決辦法
阿新 • • 發佈:2019-01-06
最近公司專案要求把從伺服器讀取的圖片存到本地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)。傻眼了,不科學啊,怎麼會把檔案編譯成資料夾呢。好吧,第一時間,發揮天才般的大腦。。。。。算了,還是找度娘吧,看了網上的方法,總結了一下:
- 可能是許可權的問題,也就是沒有加訪問SD卡的許可權;
- 可能是路徑問題,有可能路徑不存在導致的。
File file = new File(dir, "header.jpg")
改為:File file = new File(dir.getPath(), "header.jpg")
就可以了。