AssetManager in android

Basically, Assets are a raw approach to resource management. We can place any files we want into the assets directory of our project.

If we have a reference to any Context subclass, such as an Activity, we can get a reference to the AssetManager instance provided by the platform:

  1. AssetManager assetManager = getAssets();

Once we have an AssetManager reference, we can just open a raw InputStream for any asset we put into the assets directory

Like in this way:

  1. <> InputStream input = null;
  2. <> try {
  3. <> input = assetManager.open("mytextfile.txt<> ");
  4. <> } catch (IOException e) {
  5. <> // handle
  6. <> }

Here is an example as a class having feature of text file reading via AssetManager

For instance

  1. public static class myData
  2. {
  3. public static void loadData(Context context)
  4. {
  5. try
  6. {
  7. AssetManager am = context.getAssets();
  8. InputStream is = am.open("mytextfile.txt");
  9. BufferedReader br =
  10. new BufferedReader(new InputStreamReader(is));
  11. String line = br.readLine();
  12. My_Name = line;
  13. line = br.readLine();
  14. My_Contact = Integer.parseInt(line);
  15. br.close();
  16. }
  17. catch (IOException e)
  18. {
  19. Log.e("Error", "Unable to read data from txt file");
  20. }
  21. }
  22. }