安卓(Android) 怎么从Asset文件中获取字符串

2019年10月18日21:44:45安卓(Android) 怎么从Asset文件中获取字符串已关闭评论 264 934字阅读3分6秒

1.简介

安卓(Android) 怎么从Asset文件中获取字符串?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
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");
    }
    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();
  }
}

 
继续阅读
编程十万个怎么办