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 a way to get an
InputStream
for a file in theassets
folder without aContext
,Activity
,Fragment
orApplication
. How you get the data from thatInputStream
is up to you. There are plenty of suggestions for that in other answers here.Kotlin
val is = this.javaClass.classLoader.getResourceAsStream("assets/your_file.ext")
Java
InputStream is = this.getClass().getClassLoader().getResourceAsStream("assets/your_file.ext");
A caveat is that the
this
keyword is only available within an instance method. Also, all bets are off if a customClassLoader
is in play.getAssets()
method will work when you are calling inside the Activity class.If you calling this method in non-Activity class then you need to call this method from Context which is passed from Activity class. So below is the line by you can access the method.
ContextInstance
may be passed as this of Activity class.Here is a method to read a file in assets:
Reading and writing files have always been verbose and error-prone. Avoid these answers and just use Okio instead:
cityfile.txt