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:com.pieframework.runtime.utils.Zipper.java

public static void zip(String zipFile, Map<String, File> flist) {
    byte[] buf = new byte[1024];
    try {//from   w w  w. j  ava2s .c om
        // Create the ZIP file 
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

        // Compress the files 
        for (String url : flist.keySet()) {
            FileInputStream in = new FileInputStream(flist.get(url).getPath());
            // Add ZIP entry to output stream. Zip entry should be relative
            out.putNextEntry(new ZipEntry(url));
            // Transfer bytes from the file to the ZIP file 
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // Complete the entry 
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file 
        out.close();
    } catch (Exception e) {
        throw new RuntimeException("Encountered errors zipping file " + zipFile, e);
    }
}

From source file:abfab3d.io.output.STSWriter.java

/**
 * Writes a grid out to an svx file//from w  ww.  j  av a2  s.  com
 * @param grid
 * @param file
 */
public void write(AttributeGrid grid, MaterialMaker[] makers, String[] finish, String file) {
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ZipOutputStream zos = null;

    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        zos = new ZipOutputStream(bos);

        write(grid, makers, finish, zos);
    } catch (IOException ioe) {

        ioe.printStackTrace();

    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
    }

}

From source file:io.fabric8.support.impl.SupportServiceImpl.java

@Override
public File collect() {
    String name = String.format("%s-%s", "SUPPORT", DATE_TIME_SUFFIX.format(new Date()));
    File result = null;//from w w  w  .  ja  v a 2  s.c  o  m
    ZipOutputStream file = null;
    try {
        result = File.createTempFile(name, ".zip");
        LOGGER.info("Collecting information for support in file {}", result.getAbsolutePath());

        file = new ZipOutputStream(new FileOutputStream(result));
        for (Collector collector : collectors) {
            for (Resource resource : collector.collect()) {
                collectFromResource(file, resource);
            }
        }
    } catch (IOException e) {
        LOGGER.error(
                "Exception occured while collecting support information - resulting support file may not be usable",
                e);
    } finally {
        IOHelpers.close(file);
    }

    return result;
}

From source file:cz.zcu.kiv.eegdatabase.logic.zip.ZipGenerator.java

public File generate(Experiment exp, MetadataCommand mc, Set<DataFile> dataFiles, byte[] licenseFile,
        String licenseFileName) throws Exception, SQLException, IOException {

    ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    File tempZipFile = null;// w w  w  . j av a2s  .  com

    try {
        log.debug("creating output stream");
        // create temp zip file
        tempZipFile = File.createTempFile("experimentDownload_", ".zip");
        // open stream to temp zip file
        fileOutputStream = new FileOutputStream(tempZipFile);
        // prepare zip stream
        zipOutputStream = new ZipOutputStream(fileOutputStream);

        log.debug("transforming metadata from database to xml file");
        OutputStream meta = getTransformer().transformElasticToXml(exp);
        Scenario scen = exp.getScenario();
        log.debug("getting scenario file");

        byte[] xmlMetadata = null;
        if (meta instanceof ByteArrayOutputStream) {
            xmlMetadata = ((ByteArrayOutputStream) meta).toByteArray();
        }

        ZipEntry entry;

        if (licenseFileName != null && !licenseFileName.isEmpty()) {
            zipOutputStream.putNextEntry(entry = new ZipEntry("License/" + licenseFileName));
            IOUtils.copyLarge(new ByteArrayInputStream(licenseFile), zipOutputStream);
            zipOutputStream.closeEntry();
        }

        if (mc.isScenFile() && scen.getScenarioFile() != null) {
            try {

                log.debug("saving scenario file (" + scen.getScenarioName() + ") into a zip file");
                entry = new ZipEntry("Scenario/" + scen.getScenarioName());
                zipOutputStream.putNextEntry(entry);
                IOUtils.copyLarge(scen.getScenarioFile().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();

            } catch (Exception ex) {
                log.error(ex);
            }
        }

        if (xmlMetadata != null) {
            log.debug("saving xml file of metadata to zip file");
            entry = new ZipEntry(getMetadata() + ".xml");
            zipOutputStream.putNextEntry(entry);
            zipOutputStream.write(xmlMetadata);
            zipOutputStream.closeEntry();
        }

        for (DataFile dataFile : dataFiles) {
            entry = new ZipEntry(getDataZip() + "/" + dataFile.getFilename());

            if (dataFile.getFileContent().length() > 0) {

                log.debug("saving data file to zip file");

                try {

                    zipOutputStream.putNextEntry(entry);

                } catch (ZipException ex) {

                    String[] partOfName = dataFile.getFilename().split("[.]");
                    String filename;
                    if (partOfName.length < 2) {
                        filename = partOfName[0] + "" + fileCounter;
                    } else {
                        filename = partOfName[0] + "" + fileCounter + "." + partOfName[1];
                    }
                    entry = new ZipEntry(getDataZip() + "/" + filename);
                    zipOutputStream.putNextEntry(entry);
                    fileCounter++;
                }

                IOUtils.copyLarge(dataFile.getFileContent().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();
            }
        }

        log.debug("returning output stream of zip file");
        return tempZipFile;

    } finally {

        zipOutputStream.flush();
        zipOutputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        fileCounter = 0;

    }
}

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

/**
 * This method will zip a given folder./*from   ww  w  . j av  a 2  s .c  om*/
 * 
 * @param srcFolder
 * @param destZipFile
 * @throws Exception
 */
static public String zipFolder(String srcFolder, String destZipFile) throws Exception {
    File zipFile = null;
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;

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

    fileWriter = new FileOutputStream(zipFile);
    zip = new ZipOutputStream(fileWriter);

    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();

    return zipFile.getName();
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromFile() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {/*from  ww  w. j a  va2s.  c  om*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file, name);
        assertNotNull(actual);
        assertEquals(new String(contents), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}

From source file:edu.kit.dama.util.ZipUtils.java

/**
 * Write all files located in pDirectory into a zip file specified by
 * pZipOut. The provided base path is used to keep the structure defined by
 * pDirectory within the zip file.//from w  ww .jav  a  2  s.  co  m
 *
 * Due to the fact, that we have only one single base path, pDirectory must
 * start with pBasePath to avoid unexpected zip file entries.
 *
 * @param pFiles The directory containing the input files
 * @param pBasePath The base path the will be removed from all file paths
 * before creating a new zip entry
 * @param pZipOut The zip output file
 * @throws IOException If something goes wrong, in most cases if there are
 * problems with reading the input files or writing into the output file
 */
public static void zip(File[] pFiles, String pBasePath, File pZipOut) throws IOException {
    ZipOutputStream zipOut = null;
    try {
        zipOut = new ZipOutputStream(new FileOutputStream(pZipOut));
        zip(pFiles, pBasePath, zipOut);
        zipOut.finish();
        zipOut.flush();
    } finally {
        try {
            if (zipOut != null) {
                zipOut.close();
            }
        } catch (IOException ignored) {
        }
    }
}

From source file:it.geosolutions.tools.compress.file.Compressor.java

public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) {

    if (zipFile.exists() && overwrite) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + zipFile + " overvriting");
        return zipFile;
    }/*  w  w w .  j  av  a 2s .  com*/

    // Create a buffer for reading the files
    byte[] buf = new byte[Conf.getBufferSize()];

    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(zipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);

        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    continue;
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(file.getName()));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (Exception e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
    }

    return zipFile;
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream.//from www . j  a  v  a 2s  .  com
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:azkaban.utils.Utils.java

public static void zip(File input, File output) throws IOException {
    FileOutputStream out = new FileOutputStream(output);
    ZipOutputStream zOut = new ZipOutputStream(out);
    try {/*from   www  .  j ava 2s.c om*/
        zipFile("", input, zOut);
    } finally {
        zOut.close();
    }
}