Java tutorial
//package com.java2s; //License from project: Apache License import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; public class Main { /** * Add a zip entry into the provided <code>ZipOutputStream</code>. The zip * entry is the part of <code>filePathToZip</code> truncated with the * <code>baseFolderPath</code>. * <p> * So a file or folder <code>c:\my\base\folder\my\file\to\zip.txt</code> * will be added in archive using <code>my/file/to/zip.txt</code> entry. */ public static void addZipEntry(ZipOutputStream zos, File fileToZip, File baseFolder) { if (!baseFolder.isDirectory()) { throw new IllegalArgumentException(baseFolder.getPath() + " is not a directory."); } if (fileToZip.isDirectory()) { final File[] files = fileToZip.listFiles(); for (final File file : files) { addZipEntry(zos, file, baseFolder); } } else { final String filePathToZip; final int start; try { filePathToZip = fileToZip.getCanonicalPath(); start = baseFolder.getCanonicalPath().length() + 1; } catch (final IOException e1) { throw new IllegalStateException(e1); } final int end = filePathToZip.length(); String entryName = filePathToZip.substring(start, end); entryName = entryName.replace(File.separatorChar, '/'); final FileInputStream inputStream; try { inputStream = new FileInputStream(filePathToZip); } catch (final FileNotFoundException e) { throw new IllegalStateException(e); } addEntryInputStream(zos, entryName, inputStream); } } private static boolean addEntryInputStream(ZipOutputStream zos, String entryName, InputStream inputStream) { final ZipEntry zipEntry = new ZipEntry(entryName); try { zos.putNextEntry(zipEntry); } catch (final ZipException e) { // Ignore duplicate entry - no overwriting return false; } catch (final IOException e) { throw new RuntimeException("Error while adding zip entry " + zipEntry, e); } final int buffer = 2048; final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, buffer); int count; try { final byte data[] = new byte[buffer]; while ((count = bufferedInputStream.read(data, 0, buffer)) != -1) { zos.write(data, 0, count); } bufferedInputStream.close(); inputStream.close(); zos.closeEntry(); return true; } catch (final IOException e) { throw new RuntimeException(e); } } /** * Equivalent to {@link InputStream#read()} but without checked exceptions. */ public static int read(InputStream inputStream) { try { return inputStream.read(); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Equivalent to {@link ZipOutputStream#closeEntry()} but without checked * exception. */ public static void closeEntry(ZipOutputStream outputStream) { try { outputStream.closeEntry(); } catch (final IOException e) { throw new RuntimeException(e); } } }