DolDurma
DolDurma

Reputation: 17360

How to access a file from asset/raw directory

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

Upvotes: 29

Views: 73209

Answers (5)

Soni Mishra
Soni Mishra

Reputation: 91

In Kotlin we can achieve as-

val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
                it.readText()
            }

Upvotes: 2

ueen
ueen

Reputation: 692

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 /

Upvotes: 5

Malik Ahsan
Malik Ahsan

Reputation: 989

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

Upvotes: 47

Hussain Shabbir
Hussain Shabbir

Reputation: 15035

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

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007554

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

Upvotes: 15

Related Questions