Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Open an existing Zip file for adding new entries.
 * All existing entries in the zipped file will be copied in the new one.
 * /*  ww  w  .  ja v a 2 s . c  om*/
 * @param zipFile
 * @return
 * @throws IOException 
 * @throws ZipException 
 */
public static ZipOutputStream openExistingZipFileForExtension(File zipFile) throws IOException {
    // Rename source Zip file (Attention: the String path and name of the zipFile are preserved
    File originalFileTemp = new File(
            zipFile.getParentFile().getAbsolutePath() + "/" + String.valueOf(System.currentTimeMillis()));
    zipFile.renameTo(originalFileTemp);

    ZipFile sourceZipFile = new ZipFile(originalFileTemp);
    ZipOutputStream zipOutputStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile)));

    BufferedInputStream bufferedInputStream = null;

    try {
        // copy entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();
            zipOutputStream.putNextEntry(sourceZipFileEntry);

            bufferedInputStream = new BufferedInputStream(sourceZipFile.getInputStream(sourceZipFileEntry));

            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                zipOutputStream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedInputStream.read(bufferArray);
            }

            zipOutputStream.closeEntry();

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        zipOutputStream.flush();
        sourceZipFile.close();
        originalFileTemp.delete();

        return zipOutputStream;
    } catch (IOException e) {
        // delete existing Zip file
        if (zipFile.exists()) {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception ex) {
                }
                zipOutputStream = null;
            }
            zipFile.delete();
        }

        // revert renaming of source Zip file
        originalFileTemp.renameTo(zipFile);
        throw e;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }
    }
}

From source file:com.googlecode.dex2jar.v3.Dex2jar.java

private void saveTo(byte[] data, String name, Object dist) throws IOException {
    if (dist instanceof ZipOutputStream) {
        ZipOutputStream zos = (ZipOutputStream) dist;
        ZipEntry entry = new ZipEntry(name + ".class");
        int i = name.lastIndexOf('/');
        if (i > 0) {
            check(name.substring(0, i), zos);
        }//from ww  w .  j a  va  2  s . c  o  m
        zos.putNextEntry(entry);
        zos.write(data);
        zos.closeEntry();
    } else {
        File dir = (File) dist;
        FileUtils.writeByteArrayToFile(new File(dir, name + ".class"), data);
    }
}

From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Compress data/*  w ww.ja  v  a  2  s . c  om*/
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BZip2CompressorOutputStream cos = new BZip2CompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

From source file:com.espringtran.compressor4j.processor.GzipProcessor.java

/**
 * Compress data/* w w w .  j a v  a2 s .  com*/
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GzipCompressorOutputStream cos = new GzipCompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

From source file:de.knowwe.revisions.manager.action.DownloadRevisionZip.java

/**
 * Zips the article contents from specified date and writes the resulting
 * zip-File to the ZipOutputStream./* w w w  .  j a  v  a2  s  . c o  m*/
 * 
 * @created 22.04.2013
 * @param date
 * @param zos
 * @throws IOException
 */
private void zipRev(Date date, ZipOutputStream zos, UserActionContext context) throws IOException {
    RevisionManager revm = RevisionManager.getRM(context);
    ArticleManager am = revm.getArticleManager(date);
    Collection<Article> articles = am.getArticles();
    for (Article article : articles) {
        zos.putNextEntry(new ZipEntry(URLEncoder.encode(article.getTitle() + ".txt", "UTF-8")));
        zos.write(article.getRootSection().getText().getBytes("UTF-8"));
        zos.closeEntry();

        // Attachments
        Collection<WikiAttachment> atts = Environment.getInstance().getWikiConnector()
                .getAttachments(article.getTitle());
        for (WikiAttachment att : atts) {
            zos.putNextEntry(new ZipEntry(URLEncoder.encode(att.getParentName(), "UTF-8") + "-att/"
                    + URLEncoder.encode(att.getFileName(), "UTF-8")));
            IOUtils.copy(att.getInputStream(), zos);
            zos.closeEntry();
        }
    }
    zos.close();
}

From source file:ee.ria.xroad.common.messagelog.archive.LogArchiveCache.java

private void addAsicContainersToArchive(ZipOutputStream zipOut) throws IOException {
    for (String eachName : archiveFileNames) {
        ZipEntry entry = new ZipEntry(eachName);

        zipOut.putNextEntry(entry);//from   w  w  w.j  a v  a2s .c o  m

        try (InputStream archiveInput = Files.newInputStream(createTempAsicPath(eachName))) {
            IOUtils.copy(archiveInput, zipOut);
        }

        zipOut.closeEntry();
    }
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static void zipContainer(final IContainer container, final OutputStream os,
        final IProgressMonitor monitor) throws CoreException {
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os));
    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    // monitor.beginTask("Zipping " + container.getName(), container.get);
    container.accept(new IResourceVisitor() {
        @Override/* www  .ja v a  2 s  .c o m*/
        public boolean visit(IResource resource) throws CoreException {
            // MSLICE-1258
            for (IProjectPublishFilter filter : publishFilters)
                if (!filter.shouldInclude(resource))
                    return true;

            if (resource instanceof IFile) {
                final IFile file = (IFile) resource;
                final IPath relativePath = ResourceUtil.getRelativePath(container, file).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString());
                try {
                    out.putNextEntry(entry);
                    out.write(ResourceUtil.getContents(file));
                    out.closeEntry();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to write contents of " + file.getName(), e));
                }
            } else if (resource instanceof IFolder) {
                final IFolder folder = (IFolder) resource;
                if (folder.members().length > 0)
                    return true;
                final IPath relativePath = ResourceUtil.getRelativePath(container, folder).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString() + "/");
                try {
                    out.putNextEntry(entry);
                    out.closeEntry();
                } catch (IOException e) {
                    LogUtil.error(e);
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to compress directory " + folder.getName(), e));
                }
            }
            return true;
        }
    });
    try {
        out.close();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                "Failed to close output stream", e));
    }
}

From source file:com.wabacus.WabacusFacade.java

private static void tarFileToZip(String originFilePath, String zipFilePath) {
    if (Tools.isEmpty(originFilePath) || Tools.isEmpty(zipFilePath))
        return;//from  www . j a  va 2s.c  o  m
    int idx = originFilePath.lastIndexOf(File.separator);
    String fileName = idx > 0 ? originFilePath.substring(idx + File.separator.length()) : originFilePath;//???
    idx = fileName.lastIndexOf("_");
    if (idx > 0)
        fileName = fileName.substring(idx + 1).trim();
    try {
        FileOutputStream fout = new FileOutputStream(zipFilePath);
        ZipOutputStream zipout = new ZipOutputStream(fout);
        FileInputStream fis = new FileInputStream(originFilePath);
        zipout.putNextEntry(new ZipEntry(fileName));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            zipout.write(buffer, 0, len);
        }
        zipout.closeEntry();
        fis.close();
        zipout.close();
        fout.close();
    } catch (Exception e) {
        throw new WabacusRuntimeException("" + originFilePath + "zip", e);
    }
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ZipFileDataExporterImpl.java

private void doExportMetaInfo(ZipOutputStream zip, Charset charset, ExportFileMetaInfo metaInfo)
        throws IOException, IllegalAccessException {
    zip.putNextEntry(ExportFileEntry.META_INFO.toZipEntry());

    Set<String> lines = new TreeSet<>();
    FileUtils.extractFieldValuesFrom(metaInfo, lines);
    for (String line : lines) {
        zip.write(line.getBytes(charset));
        zip.write('\n');
    }/*from   w  ww  .j  ava  2s . c  o  m*/
    zip.closeEntry();
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zipFile//from  w w w.j  a  v  a2  s  .co  m
 * @param files
 * @throws java.io.IOException
 */
public static void addStreamsToZip(File zipFile, Map<String, InputStream> files) throws IOException {
    // get a temp file
    File tempFile = File.createTempFile(zipFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    FileUtils.deleteQuietly(tempFile);

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (Map.Entry<String, InputStream> e : files.entrySet()) {
            if (e.getKey().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            IOUtils.copy(zin, out);
        }
        entry = zin.getNextEntry();
    }
    // Close the streams
    zin.close();
    // Compress the files
    for (Map.Entry<String, InputStream> e : files.entrySet()) {
        InputStream in = e.getValue();
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(e.getKey()));
        // Transfer bytes from the file to the ZIP file

        IOUtils.copy(in, out);
        // Complete the entry
        out.closeEntry();
        IOUtils.closeQuietly(in);
    }
    // Complete the ZIP file
    IOUtils.closeQuietly(out);
    FileUtils.deleteQuietly(tempFile);
}