How to get URI from an asset File?

后端 未结 11 1487
慢半拍i
慢半拍i 2020-11-22 14:27

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

相关标签:
11条回答
  • 2020-11-22 14:41

    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.

    For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.

    0 讨论(0)
  • 2020-11-22 14:42
    InputStream is = getResources().getAssets().open("terms.txt");
    String textfile = convertStreamToString(is);
        
    public static String convertStreamToString(InputStream is)
            throws IOException {
    
        Writer writer = new StringWriter();
        char[] buffer = new char[2048];
    
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
    
        String text = writer.toString();
        return text;
    }
    
    0 讨论(0)
  • 2020-11-22 14:46

    try this :

    Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 
    

    I had did it and it worked

    0 讨论(0)
  • 2020-11-22 14:48

    Be sure ,your assets folder put in correct position.

    0 讨论(0)
  • 2020-11-22 14:48

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

    0 讨论(0)
  • 2020-11-22 14:52

    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.

    0 讨论(0)
提交回复
热议问题