Java Zip Files addFileToZip(File file, String entryName, ZipOutputStream zOut)

Here you can find the source of addFileToZip(File file, String entryName, ZipOutputStream zOut)

Description

Adds a file to the Zip file

License

Open Source License

Parameter

Parameter Description
file The file to add
entryName a parameter
zOut a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void addFileToZip(File file, String entryName, ZipOutputStream zOut) throws IOException 

Method Source Code


//package com.java2s;
import java.io.BufferedInputStream;

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  ww  w.  j a v  a  2 s.c  o  m
     * Adds a file to the Zip file
     * @param file The file to add
     * @param entryName
     * @param zOut
     * @throws IOException
     */
    public static void addFileToZip(File file, String entryName, ZipOutputStream zOut) throws IOException {
        // Don't add directories
        if (file.isDirectory()) {
            return;
        }

        int bytesRead;
        final int bufSize = 1024;
        byte buf[] = new byte[bufSize];

        ZipEntry zipEntry = new ZipEntry(entryName);
        // Set time stamp to file's
        zipEntry.setTime(file.lastModified());

        try {
            zOut.putNextEntry(zipEntry);
        } catch (IOException ex) {
            /*
             * Ignore things like duplicate entries and just carry on
             */
            return;
        }

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file), bufSize);
        while ((bytesRead = in.read(buf)) != -1) {
            zOut.write(buf, 0, bytesRead);
        }
        zOut.closeEntry();
        in.close();
    }
}

Related

  1. addFilesToZip(File zipFile, File[] files, String[] fileNames)
  2. addFileToZip(File file, String entryName, ZipOutputStream zos)
  3. addFileToZip(File file, String parentFolderName, ZipOutputStream zip)
  4. addFileToZip(File file, ZipOutputStream zos)
  5. addFileToZip(File in, File parent, ZipOutputStream out)
  6. addFileToZip(File root, File file, ZipOutputStream zos)