assets目录与res下的raw、drawable目录一样,也可用来存放资源文件,但它们三者有区别,对比总结如下表:
assets | res/raw | res/drawable | |
获取资源方式: | 文件路径+文件名 | R.raw.xxx | R.drawable.xxx |
是否被压缩: | NO | NO | YES(失真压缩) |
能否获取子目录下的资源: | YES | NO | NO |
assets
特点:可以建文件夹
1 直接读文件流
AssetManager am = context.getAssets();
InputStream inputStream = am.open(“user/user.list”);
2 webview加载html
webview.loadUrl(“file:///android_asset/user/user.html”);
res
特点:映射到R文件中来读取 (子文件夹不被识别)
InputStream is = getResources().openRawResource(R.raw.beep);
__________________________________
以上两种只读不可写,需要编辑时,可以拷贝到/data/data/包名/files 底下进行编辑
copyFromAssets(mContext, "a.txt", mContext.getFilesDir());
private boolean copyFromAssets(Context context, String fileName, String path) {
boolean copyIsFinish = false;
try {
InputStream is = context.getAssets().open(fileName);
File file = new File(path);
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] temp = new byte[1024];
int i = 0;
while ((i = is.read(temp)) > 0) {
fos.write(temp, 0, i);
}
fos.close();
is.close();
copyIsFinish = true;
} catch (IOException e) {
e.printStackTrace();
}
return copyIsFinish;
}