Example usage for java.util.zip ZipOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

Usage

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

/**
 * Compress data// w  w w.  ja  va  2s  .  c o m
 * 
 * @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/*from  w w  w  .  j av a  2  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:wsattacker.plugin.intelligentdos.model.ResultModel.java

public void save(File selectedFile) throws IOException {
    // Wrap a FileOutputStream around a ZipOutputStream
    // to store the zip stream to a file. Note that this is
    // not absolutely necessary
    FileOutputStream fileOutputStream = new FileOutputStream(selectedFile);
    ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
    try {/* w ww.  j av a2s  . co m*/
        createAttackMetaData(zipOutputStream, FILENAME_METADATA);
    } catch (JAXBException e) {
        throw new IOException(e);
    }

    int index = 1;
    for (SuccessfulAttack sa : attacks) {
        // a ZipEntry represents a file entry in the zip archive
        ZipEntry zipEntry = new ZipEntry(sa.getDoSAttack().getName() + "_a" + index + ".zip");
        zipOutputStream.putNextEntry(zipEntry);

        ZipOutputStream innerZipOutputStream = new ZipOutputStream(zipOutputStream);
        try {
            persistSA(sa, innerZipOutputStream);
        } catch (JAXBException e) {
            throw new IOException(e);
        }
        innerZipOutputStream.finish();

        // close ZipEntry to store the stream to the file
        zipOutputStream.closeEntry();
        index++;
    }

    zipOutputStream.close();
    fileOutputStream.close();
}

From source file:org.theospi.portfolio.help.HelpManagerImpl.java

public void packageGlossaryForExport(Id worksiteId, OutputStream os) throws IOException {
    getAuthzManager().checkPermission(HelpFunctionConstants.EXPORT_TERMS, getToolId());

    CheckedOutputStream checksum = new CheckedOutputStream(os, new Adler32());
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum));

    putWorksiteTermsIntoZip(worksiteId, zos);

    zos.finish();
    zos.flush();// ww  w.j a v a  2s  . c  o m
}

From source file:net.grinder.util.LogCompressUtils.java

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array//from  w  w  w .j  av a  2s .  c o m
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * Save the juror models to a set of files. The files will contain all the information needed
 * to apply the BDVal model to new samples.
 *
 * @param zipStream The stream used to write the models to
 * @param options The options associated with this model
 * @param task The classification task used for this model
 * @param splitPlan The split plan used to generat this model
 * @param writeModelMode The mode saving the model
 * @throws IOException if there is a problem writing to the files
 *//*from ww  w.j  a v  a2s  .c o  m*/
private synchronized void saveJurorModels(final ZipOutputStream zipStream, final DAVOptions options,
        final ClassificationTask task, final SplitPlan splitPlan, final WriteModel writeModelMode)
        throws IOException {
    if (!jurorModelsAreLoaded) {
        throw new IllegalStateException("juror models must be loaded before save");
    }

    // add the models directory entry for juror models (must end in "/")
    zipStream.putNextEntry(new ZipEntry(JUROR_MODEL_DIRECTORY + "/"));
    zipStream.closeEntry();

    final String jurorModelDirectory = JUROR_MODEL_DIRECTORY + "/"
            + FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(modelFilenamePrefix)) + "/";
    zipStream.putNextEntry(new ZipEntry(jurorModelDirectory));
    zipStream.closeEntry();

    for (final BDVModel jurorModel : jurorModels) {
        // NOTE: for zip files, the directory MUST use "/" regardless of OS

        final String jurorModelFilename = jurorModelDirectory
                + FilenameUtils.getName(jurorModel.getModelFilenamePrefix()) + ".zip";

        // Add ZIP entry for the model to output stream.
        zipStream.putNextEntry(new ZipEntry(jurorModelFilename));

        // Create the ZIP file for the juror
        LOG.debug("Writing juror model as entry: " + jurorModelFilename);
        final ZipOutputStream jurorZipStream = new ZipOutputStream(zipStream);
        jurorZipStream.setComment("Juror model: " + jurorModel.getModelFilenamePrefix());
        jurorModel.save(jurorZipStream, options, task, splitPlan, writeModelMode);
        jurorZipStream.finish(); // NOTE: we don't close the stream, that will close everything

        zipStream.closeEntry();
    }
}

From source file:com.navjagpal.fileshare.StreamingZipEntity.java

public void writeTo(OutputStream out) throws IOException {
    Cursor c = mContentResolver.query(FileSharingProvider.Files.CONTENT_URI,
            new String[] { FileSharingProvider.Files.Columns.DISPLAY_NAME,
                    FileSharingProvider.Files.Columns._DATA },
            FileSharingProvider.Files.Columns.FOLDER_ID + "=?", new String[] { mFolderId }, null);
    ZipOutputStream zipOut = new ZipOutputStream(out);
    byte[] buf = new byte[BUFFER_SIZE];
    while (c.moveToNext()) {
        String filename = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns.DISPLAY_NAME));
        String data = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns._DATA));
        zipOut.putNextEntry(new ZipEntry(filename));
        InputStream input = mContentResolver.openInputStream(Uri.parse(data));
        int len;//from w  w  w  .  j av a 2 s.  c o  m
        while ((len = input.read(buf)) > 0) {
            zipOut.write(buf, 0, len);
        }
        zipOut.closeEntry();
        input.close();
    }
    zipOut.finish();
    mFinished = true;
}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}/*from www .  jav  a 2 s.c  o  m*/
 */
public void copyMageTabZipToOutputStream(CaArrayEntityReference experimentRef, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    MageTabFileSet mtset = exportMageTab(experimentRef);
    ZipOutputStream zos = new ZipOutputStream(ostream);
    zos.putNextEntry(new ZipEntry(mtset.getIdf().getMetadata().getName()));
    IOUtils.write(mtset.getIdf().getContents(), zos);
    zos.putNextEntry(new ZipEntry(mtset.getSdrf().getMetadata().getName()));
    IOUtils.write(mtset.getSdrf().getContents(), zos);
    for (gov.nih.nci.caarray.external.v1_0.data.File dataFile : mtset.getDataFiles()) {
        zos.putNextEntry(new ZipEntry(dataFile.getMetadata().getName()));
        copyFileContentsToOutputStream(dataFile.getReference(), false, zos);
    }
    zos.finish();
}

From source file:ch.randelshofer.cubetwister.PreferencesTemplatesPanel.java

private void exportInternalTemplate(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportInternalTemplate
    if (exportFileChooser == null) {
        exportFileChooser = new JFileChooser();
        exportFileChooser.setFileFilter(new ExtensionFileFilter("zip", "Zip Archive"));
        exportFileChooser.setSelectedFile(
                new File(userPrefs.get("cubetwister.exportedHTMLTemplate", "CubeTwister HTML-Template.zip")));
        exportFileChooser.setApproveButtonText(labels.getString("filechooser.export"));
    }/*  w w  w .  j  a v a  2 s.c  om*/
    if (JFileChooser.APPROVE_OPTION == exportFileChooser.showSaveDialog(this)) {
        userPrefs.put("cubetwister.exportedHTMLTemplate", exportFileChooser.getSelectedFile().getPath());
        final File target = exportFileChooser.getSelectedFile();
        new BackgroundTask() {

            @Override
            public void construct() throws IOException {
                if (!target.getParentFile().exists()) {
                    target.getParentFile().mkdirs();
                }
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = getClass().getResourceAsStream("/htmltemplates.tar.bz");
                    out = new FileOutputStream(target);
                    exportTarBZasZip(in, out);
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                    }
                }
            }

            private void exportTarBZasZip(InputStream in, OutputStream out) throws IOException {
                ZipOutputStream zout = new ZipOutputStream(out);
                TarInputStream tin = new TarInputStream(new BZip2CompressorInputStream(in));

                for (TarArchiveEntry inEntry = tin.getNextEntry(); inEntry != null;) {
                    ZipEntry outEntry = new ZipEntry(inEntry.getName());
                    zout.putNextEntry(outEntry);
                    if (!inEntry.isDirectory()) {
                        Files.copyStream(tin, zout);
                    }
                    zout.closeEntry();
                }
                zout.finish();
            }
        }.start();
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutputs(ReportExecutionJob job, MimeMessageHelper messageHelper, List reportOutputs)
        throws MessagingException, JobExecutionException {
    String attachmentName = null;
    DataContainer attachmentData = job.createDataContainer();
    boolean close = true;
    ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
    try {/*from  ww  w . ja v a2 s .  c  o  m*/
        for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
            ReportOutput output = (ReportOutput) it.next();
            if (attachmentName == null)
                attachmentName = removeExtension(output.getFilename()) + ".zip";
            zipOutput(job, output, zipOut);
        }
        zipOut.finish();
        zipOut.flush();
        close = false;
        zipOut.close();
    } catch (IOException e) {
        throw new JSExceptionWrapper(e);
    } finally {
        if (close) {
            try {
                zipOut.close();
            } catch (IOException e) {
                log.error("Error closing stream", e);
            }
        }
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}