How to get URI from an asset File?

I have been trying to get the URI path for an asset file.

uri = Uri.fromFile(new File("//assets/mydemo.txt"));

When I check if the file exists I see that file doesn't exist

File f = new File(filepath);
if (f.exists() == true) {
    Log.e(TAG, "Valid :" + filepath);
} else {
    Log.e(TAG, "InValid :" + filepath);
}

Can some one tell me how I can mention the absolute path for a file existing in the asset folder


There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.

EDIT

To repair one of my comments below, the URL syntax for assets is file:///android_asset/... (note: three slashes).


The correct url is:

file:///android_asset/RELATIVEPATH

where RELATIVEPATH is the path to your resource relative to the assets folder.

Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.

This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.

EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.


Works for WebView but seems to fail on URL.openStream() . So you need to distinguish file:// protocols and handle them via AssetManager as suggested.

链接地址: http://www.djcxy.com/p/62548.html

上一篇: Android:如何从JAR文件动态加载类?

下一篇: 如何从资产文件获取URI?