I want to check, whether a file exists or not in the /assets/ folder. How could I do it? Please help.
Asked
Active
Viewed 7,912 times
4 Answers
12
I added a helper method to one of my application classes. I'm assuming that;
- the list of assets doesn't change while the app is running.
- the
List<String>
isn't a memory hog (only 78 assets in my app). - checking exists() on the List is faster than trying to open a File and handle an exception (I haven't actually profiled this).
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()` already returns boolean, no need for the ternary expression at the end of function. – Vytautas Šaltenis Aug 11 '12 at 00:55
8
You could also just try to open the stream, if it fails the file is not there and if it does not fail the file should be there:
/**
* 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;
}

Moss
- 6,002
- 1
- 35
- 40
-
This solution much more faster, then getting the whole asset's folder as list, and check the containment. (I measured ~50ms vs ~800ms on my device) – azendh Aug 01 '14 at 19:54
4
You can use Resources.openRawResourceFd(int resId)
http://developer.android.com/reference/android/content/res/Resources.html#openRawResourceFd%28int%29

Hrk
- 2,725
- 5
- 29
- 44
-
This doesn't give any method to check for file's existence. Thanks anyway. – Mudassir Nov 11 '10 at 10:30
-
1If the file doesn't exist, it will throw a NotFoundException. You can catch it and do what you want. – Hrk Nov 11 '10 at 10:46
0
You have to perform your own checks. As I know, there is no method for this job.

Chromium
- 1,073
- 1
- 9
- 25
-
5Understandable that there might not be a method for this, but if you can't provide an alternative then this shouldn't have been an answer. – Gowiem Jun 06 '12 at 16:30