如何检查Android资产资源?
我想检查/assets/文件夹中是否存在文件。如何检查Android资产资源?,android,resources,assets,Android,Resources,Assets,我想检查/assets/文件夹中是否存在文件。 我怎么做呢?请提供帮助。您可以使用资源。openrawsourcefd(intresid) 您必须自己进行检查。据我所知,此作业没有方法。我在一个应用程序类中添加了一个helper方法。我是这么想的 应用程序运行时,资产列表不会更改 列表不是内存占用器(在我的应用程序中只有78项资产) 检查列表中的exists()比尝试打开文件并处理异常要快(我实际上还没有对此进行分析) AssetManager am; 列表地图列表; /** *检查资产是否存在
我怎么做呢?请提供帮助。您可以使用资源。openrawsourcefd(intresid)
您必须自己进行检查。据我所知,此作业没有方法。我在一个应用程序类中添加了一个helper方法。我是这么想的
列表
不是内存占用器(在我的应用程序中只有78项资产)AssetManager am;
列表地图列表;
/**
*检查资产是否存在。
*
*@param assetName
*@return boolean-如果有同名资产,则为true。
*/
公共布尔校验集(字符串assetName){
if(mapList==null){
am=getAssets();
试一试{
mapList=Arrays.asList(am.list(“”));
}捕获(IOE异常){
}
}
返回mapList.contains(assetName);
}
您也可以尝试打开流,如果失败,文件不在那里,如果没有失败,文件应该在那里:
/**
* 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;
}
/**
*检查资产是否存在。如果资源的大小小于1字节,则此操作将失败。
*@param上下文
*@param路径
*@如果资产存在,则返回TRUE;否则返回FALSE
*/
公共静态布尔assetExists(上下文、字符串路径){
布尔bAssetOk=false;
试一试{
InputStream=context.getAssets().open(资产\基础\路径+路径);
stream.close();
巴塞托克=真;
}catch(filenotfounde异常){
w(“IOUtilities”,“assetExists失败:”+e.toString());
}捕获(IOE异常){
w(“IOUtilities”,“assetExists失败:”+e.toString());
}
返回巴塞托克;
}
这没有提供任何方法来检查文件是否存在。无论如何,谢谢。如果文件不存在,它将抛出NotFoundException。你可以抓住它,然后做你想做的。可以理解,可能没有一个方法来解决这个问题,但如果你不能提供一个替代方案,那么这就不应该是一个答案。List.contains()
已经返回布尔值,不需要在函数末尾使用三元表达式。这个解决方案速度更快,然后将整个资产的文件夹作为列表获取,并检查容器。(我在我的设备上测量到约50毫秒对约800毫秒)
/**
* 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;
}