How to access a file from asset/raw directory

六眼飞鱼酱① 提交于 2019-11-28 07:07:40

问题


with this below code i'm trying to access the file which is stored in asset/raw folder, but getting null and

E/ERR: file:/android_asset/raw/default_book.txt (No such file or directory)

error, my code is:

private void implementingDefaultBook() {
    String filePath = Uri.parse("file:///android_asset/raw/default_book.txt").toString();
    File   file     = new File(filePath);
    try {
        FileInputStream stream      = new FileInputStream(file);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("ERR ", e.getMessage());
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    }
}


回答1:


Place your text file in the /assets directory under the Android project and use AssetManager class as follows to access it.

AssetManager am = context.getAssets();
InputStream is = am.open("default_book.txt");

Or you can also put the file in the /res/raw directory, from where the file can be accessed by an id as follows

InputStream is = 
context.getResources().openRawResource(R.raw.default_book);



回答2:


Assets and resources are files on your development machine. They are not files on the device.

For assets, use open() on AssetManager to get an InputStream on your asset.

Also, FWIW:

  • Uri.parse("file:///android_asset/raw/default_book.txt").toString() is pointless, as it gives you the same string that you started with

  • file:///android_asset/ only works for WebView




回答3:


As the actual question wasn't sufficiently answered, here we go

InputStream is = context.getAssets().openFd("raw/"+"filename.txt")

context can be this or getActivity() or basically any other context

Important is to include the folder before the filename separated by an /




回答4:


InputStream is = getAssets().open("default_book.txt");


来源:https://stackoverflow.com/questions/45908648/how-to-access-a-file-from-asset-raw-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!