参考1:https://www.aliyun.com/jiaocheng/80561.html
参考2: https://www.2cto.com/kf/201611/569278.html
Android资源文件分类:
Android资源文件大致可以分为两种:
第一种是res目录下存放的可编译的资源文件:
这种资源文件系统会在R.java里面自动生成该资源文件的ID,所以访问这种资源文件比较简单,通过R.XXX.ID即可;
第二种是assets目录下存放的原生资源文件:
因为系统在编译的时候不会编译assets下的资源文件,所以我们不能通过R.XXX.ID的方式访问它们。那我么能不能通过该资源的绝对路径去访问它们呢?因为apk安装之后会放在/data/app/**.apk目录下,以apk形式存在,asset/res和被绑定在apk里,并不会解压到/data/data/YourApp目录下去,所以我们无法直接获取到assets的绝对路径,因为它们根本就没有。
还好Android系统为我们提供了一个AssetManager工具类。
查看官方API可知:AssetManager提供对应用程序的原始资源文件进行访问;这个类提供了一个低级别的API,它允许你以简单的字节流的形式打开和读取和应用程序绑定在一起的原始资源文件。
Api:
1、得到AssetManager
context.getAssets();
2、关闭AssetManager
AssetManager.close() ;
3、Resources和Assets 中的文件只可以读取而不能进行写的操作。
4、返回指定路径下的所有文件及目录名
final String[] list(String path) ;
5、ACCESS_STREAMING 模式打开assets下的指定文件
final InputStream open(String fileName);
6、使用显示的访问模式打开assets下的指定文件
final InputStream open(String fileName, int accessMode) ;
7、开发资源文件
AssetManager.open(String filename)
返回的是一个InputSteam类型的字节流,这里的filename必须是文件比如
(aa.txt;img/semll.jpg),而不能是文件夹。
加载多种资源文件:
1、加载assets目录下的网页:
加载assets/win8_Demo/目录下的index.html网页
webView.loadUrl("file:///android_asset/win8_Demo/index.html");
说明:这种方式可以加载assets目录下的网页,并且与网页有关的css,js,图片等文件也会的加载。
注意:文件名字不能带有空格和其他非法字符,只能英文字母大小、数字、下划线。
2、访问assets目录下的资源文件:
Bitmap image = null;
AssetManager am = getResources().getAssets();
try {
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
3、获取assets下的某个目录下的文件路径
List fileNames = null;
try {
String files[] =context.getAssets().list(path);
fileNames = Arrays.asList(files[]);
} catch (IOException e) {
e.printStackTrace();
}