Here you can find the source of addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath)
Parameter | Description |
---|---|
zipOutputStream | stream to add the file to |
file | the file to add. It is assumed that it is a file and not a directory. |
basePath | the base path for determining the name of the zip entry |
Parameter | Description |
---|---|
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
//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 { /**/*from www. ja va 2 s .c o m*/ * 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); } } } }