Here you can find the source of zip(final String sourceFileDir, final String zipFile)
Parameter | Description |
---|---|
zipFile | output ZIP file location |
sourceFileDir | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
FileNotFoundException | an exception |
public static void zip(final String sourceFileDir, final String zipFile) throws FileNotFoundException, IOException
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**//from ww w. j a v a 2 s . c o m * Zip it * @param zipFile output ZIP file location * @param sourceFileDir * @throws IOException * @throws FileNotFoundException */ public static void zip(final String sourceFileDir, final String zipFile) throws FileNotFoundException, IOException { final byte[] buffer = new byte[1024]; try (final FileOutputStream fos = new FileOutputStream(zipFile); final ZipOutputStream zos = new ZipOutputStream(fos)) { final List<File> fileList = new ArrayList<>(); generateFileList(new File(sourceFileDir), fileList); for (final File file : fileList) { final ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); try (final FileInputStream in = new FileInputStream(file)) { int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } } } } } /** * Traverse a directory and get all files, * and add the file into fileList * @param node file or directory */ private static void generateFileList(final File node, final List<File> fileList) { //add file only if (node.isFile()) { fileList.add(node); } if (node.isDirectory()) { final String[] subNote = node.list(); for (final String filename : subNote) { generateFileList(new File(node, filename), fileList); } } } }