作者:清风2602939017 | 来源:互联网 | 2023-10-14 16:18
文章内容参考:https:blog.csdn.netchuyouyinghearticledetails79891934https:www.cnblogs.comandlifear
文章内容参考:
https://blog.csdn.net/chuyouyinghe/article/details/79891934
https://www.cnblogs.com/andlife/archive/2011/06/25/2090109.html
1、创建assets文件的方法
image.png
image.png
2、读取内容
/**
* 读取assets目录下的文件,并返回字符串
*/
public static String getAssetsFile(String name) {
InputStream is = null;
BufferedInputStream bis = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuilder stringBuilder = null;
final AssetManager assetManager = ZLC.getApplicationContext().getAssets();
try {
is = assetManager.open(name);
bis = new BufferedInputStream(is);
isr = new InputStreamReader(bis);
br = new BufferedReader(isr);
stringBuilder = new StringBuilder();
String str;
while ((str = br.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (bis != null) {
bis.close();
}
if (is != null) {
is.close();
}
// assetManager.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (stringBuilder != null) {
return stringBuilder.toString();
} else {
return null;
}
}
3、一个异常的发生
上面读取内容的方法中,有一个关闭assetManager的方法:
assetManager.close();
当我在工具类中直接关闭,可能会出现如下异常:
Caused by: android.content.res.Resources$NotFoundException::File res/anim/no_anim.xml from xml type anim resource ID #0x7f050014
Exception : Caused by: java.lang.NullPointerException: asset]