private static boolean zipFolder(ZipOutputStream zos, File folder, int baseLength) { FileInputStream fis; BufferedInputStream bis = null; if (zos == null || folder == null) { Log.e(TAG, "zipFolder failed."); return false; } File[] fileList = folder.listFiles(); if (fileList == null || fileList.length == 0) { Log.e(TAG, "zipFolder failed."); return false; } for (File file : fileList) { if (file.isDirectory()) { zipFolder(zos, file, baseLength); } else { byte data[] = new byte[BUFFER_SIZE]; String unmodifiedFilePath = file.getPath(); String realPath = unmodifiedFilePath.substring(baseLength); if (Jbasx.mLog == Jbasx.LogMode.ALL) { Log.i(TAG, "Zipping: " + realPath); } try { fis = new FileInputStream(unmodifiedFilePath); bis = new BufferedInputStream(fis, BUFFER_SIZE); ZipEntry entry = new ZipEntry(realPath); zos.putNextEntry(entry); int count; while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) { zos.write(data, 0, count); } } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (bis != null) { bis.close(); } zos.flush(); zos.close(); } catch (IOException e) { e.printStackTrace(); } } } } return true; }
/** * Unzip a file. * * @param zipPath The path of the zipped source file. * @param unzipDir The directory where the file should be unzipped. * @return Whenever the operation was successful. */ public static boolean unzip(String zipPath, String unzipDir) { FileInputStream fis = null; ZipInputStream zin = null; FileOutputStream fos = null; if (!FileUtils.exists(zipPath)) { if (Jbasx.mLog == Jbasx.LogMode.ALL) { Log.e(TAG, "Zip path does not exist!"); } return false; } if (!FileUtils.mkDirs(unzipDir, true)) { if (Jbasx.mLog == Jbasx.LogMode.ALL) { Log.e(TAG, "Failed to create unzip folder."); } return false; } try { fis = new FileInputStream(zipPath); zin = new ZipInputStream(fis); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { String entryName = ze.getName(); if (Jbasx.mLog == Jbasx.LogMode.ALL) { Log.d(TAG, "Unzipping: " + entryName); } String entryPath = unzipDir + File.separator + entryName; if (ze.isDirectory()) { FileUtils.mkDirs(entryPath); } else { if (!FileUtils.create(entryPath, true)) { continue; } fos = new FileOutputStream(entryPath); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = zin.read(buffer)) != -1) { fos.write(buffer, 0, len); } } } } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (fis != null) { fis.close(); } if (zin != null) { zin.closeEntry(); zin.close(); } if (fos != null) { fos.flush(); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; }