如何查看Android资源资源?

Mud*_*sir 10 resources android assets

我想检查/ assets /文件夹中是否存在文件.我怎么能这样做?请帮忙.

小智 13

我在其中一个应用程序类中添加了一个辅助方法.我假设那个;

  1. 应用程序运行时,资产列表不会更改.
  2. List<String>不是记忆力(我的应用程序中只有78个资产).
  3. 检查List上的exists()比尝试打开File并处理异常(我实际上没有对此进行分析)要快.
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);
}
Run Code Online (Sandbox Code Playgroud)

  • `List.contains()`已经返回boolean,不需要函数末尾的三元表达式. (6认同)

Mos*_*oss 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;
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ium 0

您必须自己进行检查。据我所知,这项工作没有方法。

  • 可以理解,可能没有解决此问题的方法,但如果您无法提供替代方案,那么这不应该是一个答案。 (5认同)