Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a file from asset/raw directory

Tags:

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

like image 534
DolDurma Avatar asked Aug 27 '17 19:08

DolDurma


People also ask

How do I retrieve files from assets folder?

Right click on the assets folder, select New >> file (myText. txt) and your text. “Darkness cannot drive out darkness: only light can do that. Hate cannot drive out hate: only love can do that.”

How do I read an asset file?

If you cannot open your ASSETS file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a ASSETS file directly in the browser: Just drag the file onto this browser window and drop it.

What is raw folder in Android?

The raw (res/raw) folder is one of the most important folders and it plays a very important role during the development of android projects in android studio. The raw folder in Android is used to keep mp3, mp4, sfb files, etc. The raw folder is created inside the res folder: main/res/raw.


1 Answers

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); 
like image 72
Malik Ahsan Avatar answered Oct 29 '22 16:10

Malik Ahsan