How to Access a File from Asset/Raw Directory

How to access a file from asset/raw directory

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

Trying to get the path for a file in the assets or raw directory

I want to get the path so I can pass it to a function and load it. However, I can’t seem to get the path

That is because there is no path. Those are not files. They are entries in the APK file.

I get FileNotFoundException Exception and the and the string contains: android.content.res.AssetManager$AssetInputStream@5363f738

That is because you called toString() on an InputStream returned from the AssetManager.

Source snippet for loading the keystore

load() takes an InputStream. You do not have to use a FileInputStream. You are welcome to pass the InputStream that you get from the AssetManager to load():

KeyStore keyStoreFile = KeyStore.getInstance(KeyStore.getDefaultType());
keyStoreFile.load(resources.getAssets().open("snapzkeystore.bks"), password);

Just a quick questions, which is the best folder to put a keystore in, raw or assets?

Either should be fine. You can use openRawResource() on Resources, IIRC, to get an InputStream on a raw resource.

read file from assets

Here is what I do in an activity for buffered reading extend/modify to match your needs

BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));

// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.

UPDATE :

To open a file specifying the type simply add the type in the InputStreamReader call as follow.

BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));

// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

EDIT

As @Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That's why I wrote //process line. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.

In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.

ANOTHER EDIT

According to the comment of @Vincent I added the finally block.

Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.

CONTEXT

In a comment @LunarWatcher points out that getAssets() is a class in context. So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.

ContextInstance.getAssets();

This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.

how to get file path of asset folder in android

You could put your mp3 files at : res/raw folder.

MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.myringtone);
mediaPlayer.start();

How to read a json file from resource directory in Android Studio?

From the docs:

raw/

Arbitrary files to save in their raw form. To open these resources
with a raw InputStream, call Resources.openRawResource() with the
resource ID, which is R.raw.filename.

However, if you need access to original file names and file hierarchy,
you might consider saving some resources in the assets/ directory
(instead of res/raw/). Files in assets/ aren't given a resource ID, so
you can read them only using AssetManager.

https://developer.android.com/guide/topics/resources/providing-resources

Use a text file stored in ASSETS folder

AssetManger#open(String) will throw exception and you need handle it.

public final InputStream open(String fileName) throws IOException {
return open(fileName, ACCESS_STREAMING);
}

So you need:

   try {
InputSR = new InputStreamReader(am.open("test_scores.txt"));
BufferedRdr = new BufferedReader(InputSR);
// open input stream test_scores for reading purpose.
int i = 0;
while ((thisLine = BufferedRdr.readLine()) != null) {
// System.out.println(thisLine);

String[] parts = thisLine.split(" ");
testScoreList[i][0] = parts[0];
testScoreList[i][1] = parts[1];
i = i +1;
}
} catch (Exception e) {
e.printStackTrace();

}

How to reference a File in raw folder in Android

here are 2 functions. one to read from RAW and one from the Assets

/**
* Method to read in a text file placed in the res/raw directory of the
* application. The method reads in all lines of the file sequentially.
*/

public static void readRaw(Context ctx,int res_id) {

InputStream is = ctx.getResources().openRawResource(res_id);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
// size

// More efficient (less readable) implementation of above is the
// composite expression
/*
* BufferedReader br = new BufferedReader(new InputStreamReader(
* this.getResources().openRawResource(R.raw.textfile)), 8192);
*/

try {
String test;
while (true) {
test = br.readLine();
// readLine() returns null if no more lines in the file
if (test == null)
break;
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}

}

and from Assets folder

/**
* Read a file from assets
*
* @return the string from assets
*/

public static String getQuestions(Context ctx,String file_name) {

AssetManager assetManager = ctx.getAssets();
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
inputStream = assetManager.open(file_name);
outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
} catch (IOException e) {
}
return outputStream.toString();

}

How to get access to raw resources that I put in res folder?

InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));


Related Topics



Leave a reply



Submit