Android如何解壓assets目錄下的壓縮包檔案
阿新 • • 發佈:2018-12-15
1.工具類
/** * Created by YuShuangPing on 2018/12/15. */ public class ZipUtils { public static final String TAG = "ZIP"; public ZipUtils() { } /** * 解壓assets目錄下的zip到指定的路徑 * @param zipFileString ZIP的名稱,壓縮包的名稱:xxx.zip * @param outPathString 要解壓縮路徑 * @throws Exception */ public static void UnZipAssetsFolder(Context context, String zipFileString, String outPathString) throws Exception { ZipInputStream inZip = new ZipInputStream(context.getAssets().open(zipFileString)); ZipEntry zipEntry; String szName = ""; while ((zipEntry = inZip.getNextEntry()) != null) { szName = zipEntry.getName(); if (zipEntry.isDirectory()) { //獲取部件的資料夾名 szName = szName.substring(0, szName.length() - 1); File folder = new File(outPathString + File.separator + szName); folder.mkdirs(); } else { Log.e(TAG, outPathString + File.separator + szName); File file = new File(outPathString + File.separator + szName); if (!file.exists()) { Log.e(TAG, "Create the file:" + outPathString + File.separator + szName); file.getParentFile().mkdirs(); file.createNewFile(); } // 獲取檔案的輸出流 FileOutputStream out = new FileOutputStream(file); int len; byte[] buffer = new byte[1024]; // 讀取(位元組)位元組到緩衝區 while ((len = inZip.read(buffer)) != -1) { // 從緩衝區(0)位置寫入(位元組)位元組 out.write(buffer, 0, len); out.flush(); } out.close(); } } inZip.close(); } }
2.在Activity中呼叫:
try {
//從assets目錄下解壓zip檔案
ZipUtils.UnZipAssetsFolder(this,"download.zip", unZipPath);
showHtml();
} catch (Exception e) {
e.printStackTrace();
}