標籤:android blog http io os java sp 檔案 on
============問題描述============
哪位大神幫我看看下面的代碼,為什麼傳入Url最後得到的drawable是空呢?
// 網狀圖片先下載到本地cache目錄儲存,以imagUrl的圖片檔案名稱儲存。如果有同名檔案在cache目錄就從本地載入public static Drawable loadImageFromUrl(Context context, String imageUrl) {Drawable drawable = null;if (imageUrl == null)return null;String imagePath = "";String fileName = "";// 擷取url中圖片的檔案名稱與尾碼if (imageUrl != null && imageUrl.length() != 0) {fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);}// 圖片在手機本地的存放路徑,注意:fileName為空白的情況imagePath = context.getCacheDir() + "/" + fileName;Log.i(TAG, "imagePath = " + imagePath);File file = new File(context.getCacheDir(), fileName);// 儲存檔案System.out.println("cachedir = " + context.getCacheDir());Log.i(TAG, "file.toString()=" + file.toString());if (!file.exists() && !file.isDirectory()) {try {// 可以在這裡通過檔案名稱來判斷,是否本地有此圖片FileOutputStream fos = new FileOutputStream(file);InputStream is = new URL(imageUrl).openStream();int data = is.read();while (data != -1) {fos.write(data);data = is.read();}fos.close();is.close();// drawable = Drawable.createFromStream(// new URL(imageUrl).openStream(), file.toString() ); //// (InputStream) new URL(imageUrl).getContent();drawable = Drawable.createFromPath(file.toString());Log.i(TAG, "file.exists()不檔案存在,網上下載:" + drawable.toString());} catch (IOException e) {Log.e(TAG, e.toString() + "圖片下載及儲存時出現異常!");}} else {drawable = Drawable.createFromPath(file.toString());Log.i("test", "file.tostring():" + file.toString());Log.i("test", "file.exists()檔案存在,本地擷取:" + drawable);}return drawable;}
下面是輸出:
============解決方案1============
引用 4 樓 u014274707 的回複:
Quote: 引用 3 樓 svenwang 的回複:
Quote: 引用 2 樓 u014274707 的回複:
Quote: 引用 1 樓 svenwang 的回複:
你的問題是這麼產生的:
1.第一次調用函數,因為在本地不存在,所以去網路下載。
2.因為你在UI線程中訪問網路,所以導致異常,並在本地產生一個長度為0的空檔案。
3.第二次調用函數,因為本地檔案存在,所以執行的是else分支
4.因為檔案內容為空白,所以Drawable.createFromPath返回null
解決方案:
1.不要在UI線程中下載檔案。
2.下載檔案發生異常時刪除殘留檔案。
可問題是我並沒有在UI線程裡下載啊,logcat裡也沒有報exception,我是線上程池裡調用上面的方法的。如下:
executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);// 用線程池來做下載圖片的任務executor.execute(new Runnable() {@Overridepublic void run() {Drawable drawable = loadImageFromUrl(context, imageUrl);imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));Message message = handler.obtainMessage(0, drawable);handler.sendMessage(message);}});
那可能是下載失敗導致本地檔案內容不完整導致的。你可以檢查一下/data/data/com.roy.activity/cache/test01_upload_1.jpg
這個檔案。
下載失敗的原因是什嗎?我該怎麼做才能讓圖片正確顯示呢?
你是不是檢查了本地的/data/data/com.roy.activity/cache/test01_upload_1.jpg檔案有問題?
因為網路原因下載中斷或失敗是很常見的事情,具體的原因要看異常裡的資訊。
android圖片下載問題