2010-11-11 124 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