Gets a given file from the assets directory and returns it as a string. - Android App

Android examples for App:Assets String

Description

Gets a given file from the assets directory and returns it as a string.

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;

public class Main {

  private static final String FORMAT_UTF8 = "UTF-8";

  /**/*w  w w . j  a v  a  2 s .co  m*/
   * Gets a given file from the assets directory and returns it as a string.
   * 
   * @param context
   * @param filename
   *          A file in the assets directory of your application. A valid file
   *          would be in /assets/data.txt, which you would refer to with
   *          "data.txt".
   * @return The contents of a file as a string, otherwise null if there was an
   *         IO error.
   */
  public static String get(Context context, String filename) {
    StringBuilder sb = new StringBuilder();

    try {
      InputStream is = context.getAssets().open(filename);
      InputStreamReader isr = new InputStreamReader(is, FORMAT_UTF8);
      BufferedReader reader = new BufferedReader(isr);
      String line = null;

      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }

      reader.close();
    } catch (IOException e) {

      return null;
    }

    return sb.toString();
  }
}

Related Tutorials