android獲取assets資源
阿新 • • 發佈:2018-11-16
android獲取assets資源
1.載入assets目錄下的網頁
webView.loadUrl("file:///android_asset/Demo1/index.html");
2.訪問assets目錄下的資原始檔
String name = "hallo.txt";
InputStream resourceAsStream = getClass().getResourceAsStream("/assets/" + name);
3.獲取assets的檔案及目錄名
String fileNames[] =context.getAssets().list(path);
4.將assets下的檔案複製到SD卡
public void copyFilesFassets(Context context, String oldPath, String newPath) {
try {
String fileNames[] = context.getAssets().list(oldPath);//獲取assets目錄下的所有檔案及目錄名
if (fileNames.length > 0) {//如果是目錄
File file = new File(newPath);
file.mkdirs();//如果資料夾不存在,則遞迴
for (String fileName : fileNames) {
copyFilesFassets(context, oldPath + "/" + fileName, newPath + "/" + fileName);
}
} else {//如果是檔案
InputStream is = context.getAssets().open(oldPath);
FileOutputStream fos = new FileOutputStream(new File(newPath));
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = is.read(buffer)) != -1) {//迴圈從輸入流讀取 buffer位元組
fos.write(buffer, 0, byteCount);//將讀取的輸入流寫入到輸出流
}
fos.flush();//重新整理緩衝區
is.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}