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;
}