How to access a file from asset/raw directory

DolDurma picture DolDurma · Aug 27, 2017 · Viewed 39k times · Source

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();
    }
}

enter image description here

Answer

Malik Ahsan picture Malik Ahsan · Aug 27, 2017

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);