Here you can find the source of zipFolder(final String srcFolder, final String destZipFile)
Parameter | Description |
---|---|
srcFolder | the src folder |
destZipFile | the dest zip file |
public static void zipFolder(final String srcFolder, final String destZipFile)
//package com.java2s; /*/* www.j a v a 2 s .co m*/ * FileUtil.java * Copyright (c) 2014, CODEROAD, All Rights Reserved. * * This software is the confidential and proprietary information of CODEROAD * ("Confidential Information"). You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you entered into with * CODEROAD. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /** The Constant SLASH. */ private static final String SLASH = "/"; /** * Zip folder. * * @param srcFolder the src folder * @param destZipFile the dest zip file */ public static void zipFolder(final String srcFolder, final String destZipFile) { try { final FileOutputStream fileWriter = new FileOutputStream(destZipFile); final ZipOutputStream zip = new ZipOutputStream(fileWriter); addFolderToZip("", srcFolder, zip); zip.flush(); zip.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Adds the folder to zip. * * @param path the path * @param srcFolder the src folder * @param zip the zip */ private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) { final File folder = new File(srcFolder); if (folder.list().length == 0) { addFileToZip(path, srcFolder, zip, true); } else { for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false); } } } } /** * Adds the file to zip. * * @param path the path * @param srcFile the src file * @param zip the zip * @param flag the flag */ private static void addFileToZip(final String path, final String srcFile, final ZipOutputStream zip, boolean flag) { try { final File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { final byte[] buf = new byte[1024]; int len; final FileInputStream inputStream = new FileInputStream(srcFile); zip.putNextEntry( new ZipEntry(new StringBuilder(path).append(SLASH).append(folder.getName()).toString())); while (inputStream.read(buf) > 0) { len = inputStream.read(buf); zip.write(buf, 0, len); } inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }