Here you can find the source of zipFiles(List
Parameter | Description |
---|---|
files | the list of files/directories to be archived |
output | the ZIP archived file |
public static void zipFiles(List<File> files, File output)
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**/* ww w . j a va 2s. com*/ * Create a ZIP archive of a list of files. * The input list of files may contains files and/or directories. * The algorithm used to browse directories is not recursive. * @param files the list of files/directories to be archived * @param output the ZIP archived file */ public static void zipFiles(List<File> files, File output) { try { FileOutputStream fos = new FileOutputStream(output); ZipOutputStream zos = new ZipOutputStream(fos); Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return f1.getAbsolutePath().compareTo(f2.getAbsolutePath()); } }); File baseDirectory = files.get(0).getParentFile(); Deque<File> entries = new ArrayDeque<File>(files); while (!entries.isEmpty()) { File entry = entries.poll(); if (entry.isDirectory()) { for (File current : entry.listFiles()) { entries.add(current); } } else if (entry.isFile()) { ZipEntry ze = new ZipEntry( entry.getAbsolutePath().substring(baseDirectory.getAbsolutePath().length() + 1)); // ZipEntry ze = new ZipEntry(entry.getName()); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(entry); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } } zos.closeEntry(); zos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }