2010-11-11 152 views

回答

4

你必須執行自己的檢查。據我所知,這項工作沒有辦法。

+0

我也這麼認爲。謝謝。 – Mudassir 2010-12-13 08:45:54

+3

可以理解,這可能沒有辦法,但如果你不能提供替代方案,那麼這不應該是一個答案。 – Gowiem 2012-06-06 16:30:17

13

我在我的一個應用程序類中添加了一個輔助方法。我假設;

  1. 資產列表在應用程序運行時不會更改。
  2. List<String>不是內存豬(我的應用程序中只有78個資產)。
  3. 檢查列表上的exists()比試圖打開一個文件並處理異常(我沒有實際分析過這個)要快。
AssetManager am; 
List<String> mapList; 

/** 
* Checks if an asset exists. 
* 
* @param assetName 
* @return boolean - true if there is an asset with that name. 
*/ 
public boolean checkIfInAssets(String assetName) { 
    if (mapList == null) { 
     am = getAssets(); 
     try { 
      mapList = Arrays.asList(am.list("")); 
     } catch (IOException e) { 
     } 
    } 
    return mapList.contains(assetName); 
} 
+6

'List.contains()'已經返回布爾值,不需要函數結尾的三元表達式。 – 2012-08-11 00:55:23

9

你也可以只嘗試打開該流,如果它失敗的文件不存在,如果它沒有失敗的文件應該有:

/** 
* Check if an asset exists. This will fail if the asset has a size < 1 byte. 
* @param context 
* @param path 
* @return TRUE if the asset exists and FALSE otherwise 
*/ 
public static boolean assetExists(Context context, String path) { 
    boolean bAssetOk = false; 
    try { 
     InputStream stream = context.getAssets().open(ASSET_BASE_PATH + path); 
     stream.close(); 
     bAssetOk = true; 
    } catch (FileNotFoundException e) { 
     Log.w("IOUtilities", "assetExists failed: "+e.toString()); 
    } catch (IOException e) { 
     Log.w("IOUtilities", "assetExists failed: "+e.toString()); 
    } 
    return bAssetOk; 
} 
+0

該解決方案要快得多,然後將整個資產的文件夾作爲列表,並檢查包容。 (我在我的設備上測量了〜50ms vs〜800ms) – azendh 2014-08-01 19:54:34