get String From Asset File - Android App

Android examples for App:Assets String

Description

get String From Asset File

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;

public class Main {
  public static String getStringFromAssetFile(Context ctx, String filename) {

    if (ctx == null) {
      throw new RuntimeException("Sorry your app context is null");
    }/*from w w w .  j  a  va 2 s .  com*/
    try {
      AssetManager am = ctx.getAssets();
      InputStream is = am.open(filename);
      String s = convertStreamToString(is);
      is.close();
      return s;
    } catch (FileNotFoundException e) {

      throw new RuntimeException("Sorry not able to find file " + filename, e);
    } catch (IOException x) {
      throw new RuntimeException("Sorry not able to read filename:" + filename,
          x);
    }
  }

  private static String convertStreamToString(InputStream is)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i = is.read();
    while (i != -1) {
      baos.write(i);
      i = is.read();
    }
    return baos.toString();
  }
}

Related Tutorials