Here you can find the source of addDirectoryToZip(ZipOutputStream zipOutputStream, File dirToZip, String basePath, File fileToExclude)
Parameter | Description |
---|---|
zipOutputStream | the stream to add the files to |
dirToZip | the directory to zip |
basePath | the base path for determining the name of the zip entry |
fileToExclude | an optional file to not add to the zip, for instance if the zip file is created in the directory to zip |
Parameter | Description |
---|---|
IOException | in case reading the files to write or writing to the zip failed |
private static void addDirectoryToZip(ZipOutputStream zipOutputStream, File dirToZip, String basePath, File fileToExclude) throws IOException
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**// w w w. ja v a 2 s . c o m * Add the content of a directory recursively to the zip. * * @param zipOutputStream * the stream to add the files to * @param dirToZip * the directory to zip * @param basePath * the base path for determining the name of the zip entry * @param fileToExclude * an optional file to not add to the zip, for instance if the zip file is created in * the directory to zip * @throws IOException * in case reading the files to write or writing to the zip failed */ private static void addDirectoryToZip(ZipOutputStream zipOutputStream, File dirToZip, String basePath, File fileToExclude) throws IOException { for (File file : dirToZip.listFiles()) { if (file.isDirectory()) { addDirectoryToZip(zipOutputStream, file, basePath, fileToExclude); } else if (!file.equals(fileToExclude)) { addFileToZip(zipOutputStream, file, basePath); } } } /** * Add a file to the zip. The name of the zip entry will be relative to the given basePath. * * @param zipOutputStream * stream to add the file to * @param file * the file to add. It is assumed that it is a file and not a directory. * @param basePath * the base path for determining the name of the zip entry * @throws IOException * in case reading the files to write or writing to the zip failed */ private static void addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath) throws IOException { // get relative file name starting after the base path, have to add 1 to length for // path-separator character String relativeFilename = file.getCanonicalPath().substring(basePath.length() + 1, file.getCanonicalPath().length()); ZipEntry zipEntry = new ZipEntry(relativeFilename); zipOutputStream.putNextEntry(zipEntry); try (FileInputStream fileInputStream = new FileInputStream(file);) { byte[] inputBuffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(inputBuffer)) != -1) { zipOutputStream.write(inputBuffer, 0, bytesRead); } } } }