将给定的根目录及其所有底层文件夹和文件压缩到目标文件,保留文件层次结构。
/* 来自 *时代Java公众号 - N o w J a v a . c o m*/ import java.io.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.swing.filechooser.FileFilter; public class Main{ private static final FileFilter ZIP_FILE_FILTER = new FileFilter() { @Override/*时代Java - nowjava.com 提 供*/ public boolean accept(File pathname) { return pathname.getName().endsWith(ZIP_FILE_EXTENSION); } @Override public String getDescription() { // TODO Auto-generated method stub return null; } }; /** * Compress the given root and all its underlying folders and files to the * target file, preserving files hierarchy. * * @param root * The root of the Zip archive * @param target * The target archive file (must be a valid Zip file name) * @throws IOException * If an error occurs during the process */ public static void zipDirectory(final File root, final File target) throws IOException { if (!ZIP_FILE_FILTER.accept(target)) { throw new IllegalArgumentException("Target file " + target.getName() + " is not a valid Zip file name"); } byte[] buffer = new byte[1024]; FileOutputStream fileOutputStream = null; ZipOutputStream zipOutputStream = null; try { fileOutputStream = new FileOutputStream(target); zipOutputStream = new ZipOutputStream(fileOutputStream); FileInputStream fileInputStream = null; for (File file : ZipUtils.listFilesRecursive(root)) { ZipEntry entry = new ZipEntry(ZipUtils.stripRootInclusive( file, root).getPath()); zipOutputStream.putNextEntry(entry); try { fileInputStream = new FileInputStream(file); int length; while ((length = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, length); } } finally { fileInputStream.close(); } zipOutputStream.closeEntry(); } } finally { zipOutputStream.close(); } } /** * List all files and folders from the given root. * * @param root * The root of the listing * @return A list of the files under the given root */ public static List<File> listFilesRecursive(final File root) { List<File> packedFiles = new ArrayList<File>(); File[] subFiles = root.listFiles(); if (subFiles == null) { return packedFiles; } for (File file : subFiles) { if (file.isFile()) { File packedFile = new File(root, file.getName()); packedFiles.add(packedFile); } else if (file.isDirectory()) { packedFiles.addAll(ZipUtils.listFilesRecursive(file)); } } return packedFiles; }