Example usage for java.util.zip ZipOutputStream ZipOutputStream

List of usage examples for java.util.zip ZipOutputStream ZipOutputStream

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream ZipOutputStream.

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:Main.java

public static void zip(String zipFilePath, List<String> sourceFiles, String baseFolderPath, Boolean OverWrite)
        throws Exception {
    File zipFile = new File(zipFilePath);
    if (zipFile.exists() && !OverWrite)
        return;// ww  w  .java  2 s . c  o  m
    else if (zipFile.exists() && OverWrite)
        zipFile.delete();

    ZipOutputStream zos = null;
    FileOutputStream outStream = null;
    outStream = new FileOutputStream(zipFile);
    zos = new ZipOutputStream(outStream);

    if (baseFolderPath == null)
        baseFolderPath = "";

    for (String item : sourceFiles) {
        String itemName = (item.startsWith(File.separator) || baseFolderPath.endsWith(File.separator)) ? item
                : (File.separator + item);

        if (baseFolderPath.equals("")) //absolute path
            addFileToZip(baseFolderPath + itemName, zos);
        else
            //relative path
            addFileToZip(baseFolderPath + itemName, baseFolderPath, zos);

    }
    zos.flush();
    zos.close();

}

From source file:de.thischwa.pmcms.tool.compression.Zip.java

/**
 * Static method to compress all files based on the ImputStream in 'entries' into 'zip'. 
 * Each entry has a InputStream and its String representation in the zip.
 * //from w  ww. j  av  a  2 s.  c o m
 * @param zip The zip file. It will be deleted if exists. 
 * @param entries Map<File, String>
 * @param monitor Must be initialized correctly by the caller.
 * @throws IOException
 */
public static void compress(final File zip, final Map<InputStream, String> entries,
        final IProgressMonitor monitor) throws IOException {
    if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet()))
        throw new IllegalArgumentException("One ore more parameters are empty!");
    if (zip.exists())
        zip.delete();
    else if (!zip.getParentFile().exists())
        zip.getParentFile().mkdirs();

    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)));
    out.setLevel(Deflater.BEST_COMPRESSION);
    try {
        for (InputStream inputStream : entries.keySet()) {
            // skip beginning slash, because can cause errors in other zip apps
            ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream)));
            out.putNextEntry(zipEntry);
            IOUtils.copy(inputStream, out);
            out.closeEntry();
            inputStream.close();
            if (monitor != null)
                monitor.worked(1);
        }
    } finally { // cleanup
        IOUtils.closeQuietly(out);
    }
}

From source file:com.plotsquared.iserver.util.FileUtils.java

/**
 * Add files to a zip file//from www  . ja  v a 2 s .c o  m
 *
 * @param zipFile Zip File
 * @param files   Files to add to the zip
 * @param delete  If the original files should be deleted
 * @throws Exception If anything goes wrong
 */
public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception {
    Assert.notNull(zipFile, files);

    if (!zipFile.exists()) {
        if (!zipFile.createNewFile()) {
            throw new RuntimeException("Couldn't create " + zipFile);
        }
    }

    final File temporary = File.createTempFile(zipFile.getName(), "");
    //noinspection ResultOfMethodCallIgnored
    temporary.delete();

    if (!zipFile.renameTo(temporary)) {
        throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary);
    }

    final byte[] buffer = new byte[1024 * 16]; // 16mb

    ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary));
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry e = zis.getNextEntry();
    while (e != null) {
        String n = e.getName();

        boolean no = true;
        for (File f : files) {
            if (f.getName().equals(n)) {
                no = false;
                break;
            }
        }

        if (no) {
            zos.putNextEntry(new ZipEntry(n));
            int len;
            while ((len = zis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
        e = zis.getNextEntry();
    }
    zis.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(file.getName()));

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        zos.closeEntry();
        in.close();
    }
    zos.close();
    temporary.delete();

    if (delete) {
        for (File f : files) {
            f.delete();
        }
    }
}

From source file:com.dv.util.DataViewerZipUtil.java

/**
 * ??./*from  w  w w  . ja  va  2  s  .c om*/
 *
 * @param srcFile ?
 * @param outputStream ??
 */
private static void zipFile(File srcFile, OutputStream outputStream) {
    zipFile(srcFile, new ZipOutputStream(outputStream));
}

From source file:com.youTransactor.uCube.LogManager.java

public static void getLogs(OutputStream out) throws IOException {
    File logDir = context.getDir(LOG_DIR, Context.MODE_PRIVATE);

    if (logDir.listFiles().length > 0) {
        ZipOutputStream zout = new ZipOutputStream(out);

        for (File file : logDir.listFiles()) {
            ZipEntry entry = new ZipEntry(file.getName());
            zout.putNextEntry(entry);//from  www. j a  v a  2s  . c  o m
            IOUtils.copy(new FileInputStream(file), zout);
            zout.closeEntry();
        }

        zout.close();
    }
}

From source file:de.xwic.appkit.core.util.ZipUtil.java

/**
 * Zips the files array into a file that has the name given as parameter.
 * /*w w  w  . j  a v  a2s .  c  o  m*/
 * @param files
 *            the files array
 * @param zipFileName
 *            the name for the zip file
 * @return the new zipped file
 * @throws IOException
 */
public static File zip(File[] files, String zipFileName) throws IOException {

    FileOutputStream stream = null;
    ZipOutputStream out = null;
    File archiveFile = null;

    try {

        if (!zipFileName.endsWith(".zip")) {
            zipFileName = zipFileName + ".zip";
        }

        archiveFile = new File(zipFileName);
        byte buffer[] = new byte[BUFFER_SIZE];

        // Open archive file
        stream = new FileOutputStream(archiveFile);
        out = new ZipOutputStream(stream);

        for (int i = 0; i < files.length; i++) {

            if (null == files[i] || !files[i].exists() || files[i].isDirectory()) {
                continue;
            }

            log.info("Zipping " + files[i].getName());

            // Add archive entry
            ZipEntry zipAdd = new ZipEntry(files[i].getName());
            zipAdd.setTime(files[i].lastModified());
            out.putNextEntry(zipAdd);

            // Read input & write to output
            FileInputStream in = new FileInputStream(files[i]);
            while (true) {

                int nRead = in.read(buffer, 0, buffer.length);

                if (nRead <= 0) {
                    break;
                }

                out.write(buffer, 0, nRead);
            }

            in.close();
        }

    } catch (IOException e) {

        log.error("Error: " + e.getMessage(), e);
        throw e;

    } finally {

        try {

            if (null != out) {
                out.close();
            }

            if (null != stream) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Error: " + e.getMessage(), e);
            throw e;
        }

    }

    return archiveFile;

}

From source file:au.com.jwatmuff.eventmanager.util.ZipUtils.java

public static void zipFolder(File srcFolder, File zipFile, boolean rootFolder) throws IOException {
    ZipOutputStream out = null;/*from   w w  w  . j  a  va  2s . co  m*/
    try {
        //create ZipOutputStream object
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        String baseName;
        if (rootFolder) {
            //get path prefix so that the zip file does not contain the whole path
            // eg. if folder to be zipped is /home/lalit/test
            // the zip file when opened will have test folder and not home/lalit/test folder
            int len = srcFolder.getAbsolutePath().lastIndexOf(File.separator);
            baseName = srcFolder.getAbsolutePath().substring(0, len + 1);
        } else {
            baseName = srcFolder.getAbsolutePath();
        }

        addFolderToZip(srcFolder, out, baseName);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:fr.univrouen.poste.services.ZipService.java

public void writeZip(List<PosteCandidature> posteCandidatures, OutputStream destStream)
        throws IOException, SQLException {

    ZipOutputStream out = new ZipOutputStream(destStream);

    for (PosteCandidature posteCandidature : posteCandidatures) {
        String folderName = posteCandidature.getPoste().getNumEmploi().concat("/");
        folderName = folderName.concat(posteCandidature.getCandidat().getNom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getPrenom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getNumCandidat().concat("/"));
        for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) {
            String fileName = posteCandidatureFile.getId().toString().concat("-")
                    .concat(posteCandidatureFile.getFilename());
            String folderFileName = folderName.concat(fileName);
            out.putNextEntry(new ZipEntry(folderFileName));
            InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream();
            BufferedInputStream bufInputStream = new BufferedInputStream(inputStream, BUFFER);
            byte[] bytes = new byte[BUFFER];
            int length;
            while ((length = bufInputStream.read(bytes)) >= 0) {
                out.write(bytes, 0, length);
            }/* ww w.j a va  2 s .  com*/
            out.closeEntry();
        }
    }
    out.close();
}

From source file:com.recomdata.transmart.data.export.util.ZipUtil.java

/**
 * This method will bundle all the files into a zip file. 
 * If there are 2 files with the same name, only the first file is part of the zip.
 * /*from   w  w  w .  ja  v  a 2 s.  c om*/
 * @param zipFileName
 * @param files
 * 
 * @return zipFile absolute path
 * 
 */
public static String bundleZipFile(String zipFileName, List<File> files) {
    File zipFile = null;
    Map<String, File> filesMap = new HashMap<String, File>();

    if (StringUtils.isEmpty(zipFileName))
        return null;

    try {
        zipFile = new File(zipFileName);
        if (zipFile.exists() && zipFile.isFile() && zipFile.delete()) {
            zipFile = new File(zipFileName);
        }

        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        zipOut.setLevel(ZipOutputStream.DEFLATED);
        byte[] buffer = new byte[BUFFER_SIZE];

        for (File file : files) {
            if (filesMap.containsKey(file.getName())) {
                continue;
            } else if (file.exists() && file.canRead()) {
                filesMap.put(file.getName(), file);
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                FileInputStream fis = new FileInputStream(file);
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    zipOut.write(buffer, 0, bytesRead);
                }
                zipOut.flush();
                zipOut.closeEntry();
            }
        }
        zipOut.finish();
        zipOut.close();
    } catch (IOException e) {
        //log.error("Error while creating Zip file");
    }

    return (null != zipFile) ? zipFile.getAbsolutePath() : null;
}

From source file:com.mobeelizer.java.sync.MobeelizerOutputData.java

public MobeelizerOutputData(final File file, final File tmpFile) {
    try {//w  w  w .j av a2s . c  om
        zip = new ZipOutputStream(new FileOutputStream(file));
        dataFile = tmpFile;
        dataOutputStream = new BufferedOutputStream(new FileOutputStream(dataFile));
        deletedFiles = new LinkedList<String>();
    } catch (IOException e) {
        closeQuietly(zip);
        closeQuietly(dataOutputStream);
        throw new IllegalStateException(e.getMessage(), e);
    }
}