Java Zip Files addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath)

Here you can find the source of addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath)

Description

Add a file to the zip.

License

Apache License

Parameter

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

Exception

Parameter Description
IOException in case reading the files to write or writing to the zip failed

Declaration

private static void addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath)
        throws IOException 

Method Source Code


//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);
            }
        }
    }
}

Related

  1. addFileToZip(String path, File srcFile, ZipOutputStream zip, boolean flag)
  2. addFileToZip(String path, File srcFile, ZipOutputStream zip, String destZipFile)
  3. addFileToZip(String path, String srcFile, ZipOutputStream zip)
  4. addFileToZip(String path, String srcFile, ZipOutputStream zip)
  5. addFileToZip(ZipOutputStream out, InputStream in, String entry)
  6. addFileToZip(ZipOutputStream zipOutputStream, String path, byte[] bytes)
  7. addFileToZip(ZipOutputStream zos, File file, File rootDir)
  8. addFileToZipOutputStream(File file, ZipOutputStream zipOs)
  9. addToZip(byte[] zip, String file, String fileName)