Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:de.uzk.hki.da.pkg.ZipArchiveBuilder.java

private void addFileToArchive(String path, File srcFile, ZipOutputStream zip, boolean includeFolder)
        throws Exception {

    if (srcFile.isDirectory()) {
        addFolderToArchive(path, srcFile, zip, includeFolder);
    } else {/* ww  w. ja va  2 s .  c  om*/
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + srcFile.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        in.close();
    }

    zip.flush();

}

From source file:brut.directory.ZipUtils.java

private static void processFolder(final File folder, final ZipOutputStream zipOutputStream,
        final int prefixLength) throws BrutException, IOException {
    for (final File file : folder.listFiles()) {
        if (file.isFile()) {
            final String cleanedPath = BrutIO.sanitizeUnknownFile(folder,
                    file.getPath().substring(prefixLength));
            final ZipEntry zipEntry = new ZipEntry(BrutIO.normalizePath(cleanedPath));

            // aapt binary by default takes in parameters via -0 arsc to list extensions that shouldn't be
            // compressed. We will replicate that behavior
            final String extension = FilenameUtils.getExtension(file.getAbsolutePath());
            if (mDoNotCompress != null
                    && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
                zipEntry.setMethod(ZipEntry.STORED);
                zipEntry.setSize(file.length());
                BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
                CRC32 crc = BrutIO.calculateCrc(unknownFile);
                zipEntry.setCrc(crc.getValue());
                unknownFile.close();//from w w w.j a  v a2 s .  c  o  m
            } else {
                zipEntry.setMethod(ZipEntry.DEFLATED);
            }

            zipOutputStream.putNextEntry(zipEntry);
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, zipOutputStream);
            }
            zipOutputStream.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(file, zipOutputStream, prefixLength);
        }
    }
}

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;/*  w  ww .ja v 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:au.org.ala.layers.web.IntersectService.java

@RequestMapping(value = WS_INTERSECT_BATCH_DOWNLOAD, method = RequestMethod.GET)
public void batchDownload(@PathVariable("id") Long id,
        @RequestParam(value = "csv", required = false, defaultValue = "false") Boolean csv,
        HttpServletRequest request, HttpServletResponse response) {

    BatchConsumer.start(layerIntersectDao, userProperties.getProperty("batch_path"));

    try {/*from   ww w .  jav a2s .co  m*/
        Map map = new HashMap();
        BatchProducer.addInfoToMap(userProperties.getProperty("batch_path"), String.valueOf(id), map);
        if (map.get("finished") != null) {
            OutputStream os = response.getOutputStream();

            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(userProperties.getProperty("batch_path") + File.separator + id
                            + File.separator + "sample.csv"));

            if (!csv) {
                ZipOutputStream zip = new ZipOutputStream(os);
                zip.putNextEntry(new ZipEntry("sample.csv"));

                os = zip;
            }
            byte[] buffer = new byte[4096];
            int size;
            while ((size = bis.read(buffer)) > 0) {
                os.write(buffer, 0, size);
            }
            bis.close();
            os.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return;
}

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

protected void zipOutput(ReportExecutionJob job, ReportOutput output, ZipOutputStream zipOut)
        throws IOException {
    zipOut.putNextEntry(new ZipEntry(output.getFilename()));
    DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut);
    zipOut.closeEntry();//from   w w  w  .  j  a v a2  s .c o  m

    for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
        ReportOutput child = (ReportOutput) it.next();
        String childName = getChildrenFolderName(job, output.getFilename()) + '/' + child.getFilename();
        zipOut.putNextEntry(new ZipEntry(childName));
        DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut);
        zipOut.closeEntry();
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void createZipEntry(File file, ZipOutputStream zos) throws IOException {
    zos.putNextEntry(new ZipEntry(file.getName()));
    zos.write(FileUtils.readFileToByteArray(file));
    zos.closeEntry();/*from  w  ww.java2 s  . c  o  m*/
}

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

String bundleSTM(String strcsv, String stscsv, STS sts) throws ShakedownTestException {
    String tmpdir = System.getProperty("java.io.tmpdir");
    String stmpath = ConfigurationService.getProperty(ConfigKey.STM_PATH);
    if (tmpdir != null && !tmpdir.trim().isEmpty()) {
        if (stmpath != null && new File(stmpath).exists()) {
            try {
                File bundle = new File(tmpdir + File.separator + sts.getTestId() + "stm.jar");
                ZipOutputStream bundleZOS = new ZipOutputStream(new FileOutputStream(bundle));
                bundleZOS.putNextEntry(new ZipEntry("str.csv"));
                IOUtils.write(strcsv, bundleZOS);
                bundleZOS.putNextEntry(new ZipEntry("sts.csv"));
                IOUtils.write(stscsv, bundleZOS);
                ZipInputStream zin = new ZipInputStream(new FileInputStream(stmpath));
                ZipEntry ze;//  w  ww .  ja  v  a 2  s . c  o m
                while ((ze = zin.getNextEntry()) != null) {
                    bundleZOS.putNextEntry(ze);
                    IOUtils.copy(zin, bundleZOS);
                }
                bundleZOS.close();
                log.info("Successfully bundled STM and stored to " + bundle.getAbsolutePath());
            } catch (IOException e) {
                throw new ShakedownTestException("Was not able to bundle STM", e);
            }
        } else {
            throw new ShakedownTestException(
                    "No STM found at location configured with system property " + ConfigKey.STM_PATH + ".");
        }
    } else {
        throw new ShakedownTestException("No temporary folder found - is java.io.tmpdir defined?");
    }
    return tmpdir + File.separator + sts.getTestId() + "stm.jar";
}

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

private Map<String, byte[]> zipFile(ReportExecutionJob job, ReportOutput output, boolean useFolderHierarchy)
        throws IOException {
    String attachmentName;/*w w w  .  j  a va 2s . c  o m*/
    DataContainer attachmentData;

    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOut.putNextEntry(new ZipEntry(output.getFilename()));
            DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut);
            zipOut.closeEntry();

            for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
                ReportOutput child = (ReportOutput) it.next();
                String childName = child.getFilename();
                if (useFolderHierarchy)
                    childName = getChildrenFolderName(job, output.getFilename()) + '/' + childName;
                zipOut.putNextEntry(new ZipEntry(childName));
                DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut);
                zipOut.closeEntry();
            }

            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);
                }
            }
        }
        attachmentName = output.getFilename() + ".zip";
    }
    Map result = new HashMap<String, InputStream>();
    result.put(attachmentName, IOUtils.toByteArray(attachmentData.getInputStream()));
    return result;
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

@Test
public void shouldReloadIfChanged() throws Exception {
    File file = this.zip.getFile("a/b/c.txt");
    assertThat(file.getContent().asString(), is("c"));
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile));
    try {//from   w w  w. j  a  va 2s . c o m
        zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt"));
        zipOutputStream.write("c2".getBytes());
    } finally {
        zipOutputStream.close();
    }
    assertThat(file.getContent().asString(), is("c2"));
}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

@RequestMapping(value = "/export/zip", method = POST, consumes = "multipart/form-data")
@ResponseStatus(OK)//from w  w  w.  j  av  a 2s.com
public byte[] export(@RequestParam("name") String name, @RequestParam("rows") List<String> rows,
        @RequestParam("columns") List<String> columns, @RequestParam("rowSelections") String jsonRowSelections,
        @RequestParam("columnSelections") String jsonColumnSelections,
        @RequestParam("analyses") String[] analyses, HttpServletResponse response)
        throws DatasetException, IOException {
    log.info(String.format("Offline %s, %s, %s, %s", name, rows, columns, analyses));

    //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

    //nw zip entry for dataset
    Dataset dataset = workspace.get(name);
    zipOutputStream.putNextEntry(new ZipEntry("dataset.json"));
    IOUtils.copy(new ByteArrayInputStream(mapper.writeValueAsBytes(dataset)), zipOutputStream);
    zipOutputStream.closeEntry();

    zipAnnotations(name, "row", zipOutputStream);
    zipAnnotations(name, "column", zipOutputStream);

    if (dataset.values() instanceof IFlatFileValues) {
        IFlatFileValues values = (IFlatFileValues) dataset.values();
        zipOutputStream.putNextEntry(new ZipEntry("values.bin"));
        InputStream valuesIs = values.asInputStream();
        IOUtils.copy(valuesIs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        valuesIs.close();
    }

    //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
    int i = 0;
    for (String analysis : analyses) {
        InputStream analysisOs = new ByteArrayInputStream(analysis.getBytes(StandardCharsets.UTF_8));
        zipOutputStream.putNextEntry(new ZipEntry(String.format("analysis_%d.json", i)));
        JsonNode analysisJson = mapper.readTree(analysis);
        IOUtils.copy(analysisOs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        analysisOs.close();
        i++;
    }
    zipOutputStream.flush();
    zipOutputStream.close();

    byte[] ret = byteArrayOutputStream.toByteArray();
    IOUtils.closeQuietly(bufferedOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);

    response.setContentLength(ret.length);
    response.setContentType("application/zip"); //or something more generic...
    response.setHeader("Accept-Ranges", "bytes");
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", name));
    return ret;
}