26

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

DolDurma
  • 15,753
  • 51
  • 198
  • 377

5 Answers5

43

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);
Malik Ahsan
  • 931
  • 7
  • 10
  • what is context and how do you access it – Patrick Youssef Jun 25 '21 at 19:59
  • 1
    @PatrickYoussef basically Context is an object that's used to do anything related to your android app, like getting assets, you'll need a reference of your app to be able to access your app's assets. you can get this object from something like an Activity. read more about it: https://stackoverflow.com/questions/3572463/what-is-context-on-android – Iyxan23 Dec 13 '21 at 09:35
13

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

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
5

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 /

ueen
  • 692
  • 3
  • 9
  • 21
2

In Kotlin we can achieve as-

val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
                it.readText()
            }
Soni Mishra
  • 91
  • 1
  • 2
0
InputStream is = getAssets().open("default_book.txt");
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56