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; }
/** * Zip a file. * * @param filePath The path of the source file. * @param zipPath The path where the zipped file should be stored. * @return Whenever the operation was successful. */ public static boolean zip(String filePath, String zipPath) { FileInputStream fis = null; BufferedInputStream bis = null; ZipOutputStream zos = null; try { File file = new File(filePath); FileOutputStream fos = new FileOutputStream(zipPath); zos = new ZipOutputStream(new BufferedOutputStream(fos)); if (file.isDirectory()) { int baseLength = file.getParent().length() + 1; zipFolder(zos, file, baseLength); } else { byte data[] = new byte[BUFFER_SIZE]; fis = new FileInputStream(filePath); bis = new BufferedInputStream(fis, BUFFER_SIZE); String entryName = file.getName(); if (Jbasx.mLog == Jbasx.LogMode.ALL) { Log.i(TAG, "Zipping: " + entryName); } ZipEntry entry = new ZipEntry(entryName); zos.putNextEntry(entry); int count; while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) { zos.write(data, 0, count); } } } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (fis != null) { fis.close(); } if (bis != null) { bis.close(); } if (zos != null) { zos.flush(); zos.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; }