Skip to content

Instantly share code, notes, and snippets.

@Limuyang1013
Created January 4, 2016 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Limuyang1013/9c55bfbc5e3b17f3a138 to your computer and use it in GitHub Desktop.
Save Limuyang1013/9c55bfbc5e3b17f3a138 to your computer and use it in GitHub Desktop.
从assets中读取文本和图片资源
/** 从assets 文件夹中读取文本数据 */
public static String getTextFromAssets(final Context context, String fileName) {
String result = "";
try {
InputStream in = context.getResources().getAssets().open(fileName);
// 获取文件的字节数
int lenght = in.available();
// 创建byte数组
byte[] buffer = new byte[lenght];
// 将文件中的数据读到byte数组中
in.read(buffer);
result = EncodingUtils.getString(buffer, "UTF-8");
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** 从assets 文件夹中读取图片 */
public static Drawable loadImageFromAsserts(final Context ctx, String fileName) {
try {
InputStream is = ctx.getResources().getAssets().open(fileName);
return Drawable.createFromStream(is, null);
} catch (IOException e) {
if (e != null) {
e.printStackTrace();
}
} catch (OutOfMemoryError e) {
if (e != null) {
e.printStackTrace();
}
} catch (Exception e) {
if (e != null) {
e.printStackTrace();
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment