public class Utils {
public static List<Message> getMessages() {
//File file = new File("file:///android_asset/helloworld.txt");
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");
}
}
I am using this code trying to read a file from assets. I tried two ways to do this. First, when use File I received FileNotFoundException, when using AssetManager getAssets() method isn’t recognized.
Is there any solution here?
Here is what I do in an activity for buffered reading extend/modify to match your needs
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.
EDIT
As @Stan says in the comment, the code I am giving is not summing up lines.
mLineis 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
mLineat each pass usingStringBuilder()and appending each pass.ANOTHER EDIT
According to the comment of @Vincent I added the
finallyblock.Also note that in Java 7 and upper you can use
try-with-resourcesto use theAutoCloseableandCloseablefeatures of recent Java.CONTEXT
In a comment @LunarWatcher points out that
getAssets()is aclassincontext. So, if you call it outside of anactivityyou need to refer to it and pass the context instance to the activity.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.