How to read from the Assets folder in an Eclipse Android application

Seeing errors like these?


java.io.FileNotFoundException
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:315)
at android.content.res.AssetManager.open(AssetManager.java:289)

The problem is that Eclipse isn’t finding your file, because you may not be using AssetManager to retrieve plain-text files from the assets folder. Here’s how to fix this:

  1. Note that there is no file extension on text. When I pasted ‘text.txt’ into the Assets folder to begin with, it had no extension. I tried and tried to get the app to recognize that Assets had a text.txt file in there, and finally tried it with no file extension as it appeared in the folder view.
  2. The try/catch AND the throws declaration are necessary to handle Eclipse’s fiddly compiler.
  3. Don’t cry. If you still can’t figure out how to get Eclipse
    and your app to read the file, clean the project (Project –> Clean), make sure that the Assets folder is NOT on the build path, restart Eclipse, ensure you have no other errors (ADB, DDMS, anything), and try again. If it still doesn’t work, comment here and I’ll both try to help and make updates to the code.


public void openFile () throws IOException {
System.out.println("Starting openFile now");
AssetManager am = context.getAssets();
try {
InputStream is = am.open("text");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Useful links (none of which contain the entire solution, but all of which had some piece):

http://stackoverflow.com/questions/6039862/location-of-apk-file
http://stackoverflow.com/questions/5086539/reading-file-from-assets-directory-throws-filenotfoundexception
http://developer.android.com/reference/android/content/res/AssetManager.html
http://developer.android.com/reference/java/io/InputStream.html
http://stackoverflow.com/questions/5771366/reading-a-simple-text-file
http://stackoverflow.com/questions/10267594/how-to-access-
assets-folder-in-my-android-app

http://stackoverflow.com/questions/9674815/trouble-with-reading-file-from-assets-folder-in-android

7 thoughts on “How to read from the Assets folder in an Eclipse Android application”

Leave a Reply