Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream.

Prototype

public ZipArchiveOutputStream(File file) throws IOException 

Source Link

Document

Creates a new ZIP OutputStream writing to a File.

Usage

From source file:br.com.thiaguten.archive.ZipArchive.java

@Override
protected ArchiveOutputStream createArchiveOutputStream(OutputStream outputStream) {
    return new ZipArchiveOutputStream(outputStream);
}

From source file:io.github.zlika.reproducible.ZipStripper.java

@Override
public void strip(File in, File out) throws IOException {
    try (final ZipFile zip = new ZipFile(in);
            final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) {
        final List<String> sortedNames = sortEntriesByName(zip.getEntries());
        for (String name : sortedNames) {
            final ZipArchiveEntry entry = zip.getEntry(name);
            // Strip Zip entry
            final ZipArchiveEntry strippedEntry = filterZipEntry(entry);
            // Strip file if required
            final Stripper stripper = getSubFilter(name);
            if (stripper != null) {
                // Unzip entry to temp file
                final File tmp = File.createTempFile("tmp", null);
                tmp.deleteOnExit();//  w w w.java2 s  . c  o  m
                Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
                final File tmp2 = File.createTempFile("tmp", null);
                tmp2.deleteOnExit();
                stripper.strip(tmp, tmp2);
                final byte[] fileContent = Files.readAllBytes(tmp2.toPath());
                strippedEntry.setSize(fileContent.length);
                zout.putArchiveEntry(strippedEntry);
                zout.write(fileContent);
                zout.closeArchiveEntry();
            } else {
                // Copy the Zip entry as-is
                zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry));
            }
        }
    }
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory
 *///  w w w. j av a2  s .  c o m
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java

/**
 * ?/*www .  ja v  a2 s .  c  o  m*/
 *
 * @param out
 * @param filepathList
 */
public static void zip(OutputStream out, List<String> filepathList, String filenameEncoding) {
    ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(out);
    zipout.setEncoding(filenameEncoding);
    for (String path : filepathList) {
        if (StringUtil.isNull(path))
            continue;
        File file = new File(path);
        if (!file.exists())
            continue;
        zipFile(zipout, file, "");
    }
}

From source file:br.com.thiaguten.archive.ZipArchive.java

protected ArchiveOutputStream createArchiveOutputStream(Path path) throws IOException {
    // for some internal optimizations should use
    // the constructor that accepts a File argument
    return new ZipArchiveOutputStream(path.toFile());
}

From source file:com.amazonaws.codepipeline.jenkinsplugin.CompressionTools.java

public static void compressZipFile(final File temporaryZipFile, final Path pathToCompress,
        final BuildListener listener) throws IOException {
    try (final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(
            new BufferedOutputStream(new FileOutputStream(temporaryZipFile)))) {

        compressArchive(pathToCompress, zipArchiveOutputStream, new ArchiveEntryFactory(CompressionType.Zip),
                CompressionType.Zip, listener);
    }/*w  w w .j  av  a  2 s .  c om*/
}

From source file:com.glaf.core.util.ZipUtils.java

/**
 * /*from w  w  w.j  a  v a2s  .c om*/
 * ?zip?
 * 
 * @param files
 *            ?
 * 
 * @param zipFilePath
 *            ?zip ,"/var/data/aa.zip";
 */
public static void compressFile(File[] files, String zipFilePath) {
    if (files != null && files.length > 0) {
        if (isEndsWithZip(zipFilePath)) {
            ZipArchiveOutputStream zaos = null;
            try {
                File zipFile = new File(zipFilePath);
                zaos = new ZipArchiveOutputStream(zipFile);

                // Use Zip64 extensions for all entries where they are
                // required
                zaos.setUseZip64(Zip64Mode.AsNeeded);

                for (File file : files) {
                    if (file != null) {
                        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName());
                        zaos.putArchiveEntry(zipArchiveEntry);
                        InputStream is = null;
                        try {
                            is = new BufferedInputStream(new FileInputStream(file));
                            byte[] buffer = new byte[BUFFER];
                            int len = -1;
                            while ((len = is.read(buffer)) != -1) {
                                zaos.write(buffer, 0, len);
                            }

                            // Writes all necessary data for this entry.
                            zaos.closeArchiveEntry();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            IOUtils.closeStream(is);
                        }
                    }
                }
                zaos.finish();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeStream(zaos);
            }
        }
    }
}

From source file:com.gitblit.utils.CompressionUtils.java

/**
 * Zips the contents of the tree at the (optionally) specified revision and
 * the (optionally) specified basepath to the supplied outputstream.
 * //from w  w  w  . j a  va 2s .com
 * @param repository
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
public static boolean zip(Repository repository, String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
        zos.setComment("Generated by Gitblit");
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString());
            entry.setSize(reader.getObjectSize(id, Constants.OBJ_BLOB));
            entry.setComment(commit.getName());
            entry.setUnixMode(mode.getBits());
            entry.setTime(modified);
            zos.putArchiveEntry(entry);

            ObjectLoader ldr = repository.open(id);
            ldr.copyTo(zos);
            zos.closeArchiveEntry();
        }
        zos.finish();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to zip files from commit {1}", commit.getName());
    } finally {
        tw.release();
        rw.dispose();
    }
    return success;
}

From source file:com.mirth.connect.util.ArchiveUtils.java

/**
 * Create an archive file from files/sub-folders in a given source folder.
 * /*from   ww w .  j av  a 2s . com*/
 * @param sourceFolder
 *            Sub-folders and files inside this folder will be copied into the archive
 * @param destinationFile
 *            The destination archive file
 * @param archiver
 *            The archiver format, see
 *            org.apache.commons.compress.archivers.ArchiveStreamFactory
 * @param compressor
 *            The compressor format, see
 *            org.apache.commons.compress.compressors.CompressorStreamFactory
 * @throws CompressException
 */
public static void createArchive(File sourceFolder, File destinationFile, String archiver, String compressor)
        throws CompressException {
    if (!sourceFolder.isDirectory() || !sourceFolder.exists()) {
        throw new CompressException("Invalid source folder: " + sourceFolder.getAbsolutePath());
    }

    logger.debug("Creating archive \"" + destinationFile.getAbsolutePath() + "\" from folder \""
            + sourceFolder.getAbsolutePath() + "\"");
    OutputStream outputStream = null;
    ArchiveOutputStream archiveOutputStream = null;

    try {
        /*
         * The commons-compress documentation recommends constructing a ZipArchiveOutputStream
         * with the archive file when using the ZIP archive format. See
         * http://commons.apache.org/proper/commons-compress/zip.html
         */
        if (archiver.equals(ArchiveStreamFactory.ZIP) && compressor == null) {
            archiveOutputStream = new ZipArchiveOutputStream(destinationFile);
        } else {
            // if not using ZIP format, use the archiver/compressor stream factories to initialize the archive output stream
            outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));

            if (compressor != null) {
                outputStream = new CompressorStreamFactory().createCompressorOutputStream(compressor,
                        outputStream);
            }

            archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiver, outputStream);
        }

        createFolderArchive(sourceFolder, archiveOutputStream,
                sourceFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR);
    } catch (Exception e) {
        throw new CompressException(e);
    } finally {
        IOUtils.closeQuietly(archiveOutputStream);
        IOUtils.closeQuietly(outputStream);
        logger.debug("Finished creating archive \"" + destinationFile.getAbsolutePath() + "\"");
    }
}

From source file:adams.core.io.ZipUtils.java

/**
 * Creates a zip file from the specified files.
 *
 * @param output   the output file to generate
 * @param files   the files to store in the zip file
 * @param stripRegExp   the regular expression used to strip the file names (only applied to the directory!)
 * @param bufferSize   the buffer size to use
 * @return      null if successful, otherwise error message
 *//*from w w  w. jav  a 2 s .  c  o  m*/
@MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html")
public static String compress(File output, File[] files, String stripRegExp, int bufferSize) {
    String result;
    int i;
    byte[] buf;
    int len;
    ZipArchiveOutputStream out;
    BufferedInputStream in;
    FileInputStream fis;
    FileOutputStream fos;
    String filename;
    String msg;
    ZipArchiveEntry entry;

    in = null;
    fis = null;
    out = null;
    fos = null;
    result = null;
    try {
        // does file already exist?
        if (output.exists())
            System.err.println("WARNING: overwriting '" + output + "'!");

        // create ZIP file
        buf = new byte[bufferSize];
        fos = new FileOutputStream(output.getAbsolutePath());
        out = new ZipArchiveOutputStream(new BufferedOutputStream(fos));
        for (i = 0; i < files.length; i++) {
            fis = new FileInputStream(files[i].getAbsolutePath());
            in = new BufferedInputStream(fis);

            // Add ZIP entry to output stream.
            filename = files[i].getParentFile().getAbsolutePath();
            if (stripRegExp.length() > 0)
                filename = filename.replaceFirst(stripRegExp, "");
            if (filename.length() > 0)
                filename += File.separator;
            filename += files[i].getName();
            entry = new ZipArchiveEntry(filename);
            entry.setSize(files[i].length());
            out.putArchiveEntry(entry);

            // Transfer bytes from the file to the ZIP file
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);

            // Complete the entry
            out.closeArchiveEntry();
            FileUtils.closeQuietly(in);
            FileUtils.closeQuietly(fis);
            in = null;
            fis = null;
        }

        // Complete the ZIP file
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
        out = null;
        fos = null;
    } catch (Exception e) {
        msg = "Failed to generate archive '" + output + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
    }

    return result;
}