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:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zipFile// w w w .ja v  a 2  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);
}

From source file:ch.rgw.tools.StringTool.java

/**
 * Eine Hashtable in ein komprimiertes Byte-Array umwandeln
 * // w w  w. j av  a  2  s  .co m
 * @param hash
 *            die Hashtable
 * @param compressMode
 *            GLZ, HUFF, BZIP2
 * @param ExtInfo
 *            Je nach Kompressmode ntige zusatzinfo
 * @return das byte-Array mit der komprimierten Hashtable
 * @deprecated compressmode is always ZIP now.
 */
@SuppressWarnings("unchecked")
@Deprecated
public static byte[] flatten(final Hashtable hash, final int compressMode, final Object ExtInfo) {
    ByteArrayOutputStream baos = null;
    OutputStream os = null;
    ObjectOutputStream oos = null;
    try {
        baos = new ByteArrayOutputStream(hash.size() * 30);
        switch (compressMode) {
        case GUESS:
        case ZIP:
            os = new ZipOutputStream(baos);
            ((ZipOutputStream) os).putNextEntry(new ZipEntry("hash"));
            break;
        case BZIP:
            os = new CBZip2OutputStream(baos);
            break;
        case HUFF:
            os = new HuffmanOutputStream(baos, (HuffmanTree) ExtInfo, 0);
            break;
        case GLZ:
            os = new GLZOutputStream(baos, hash.size() * 30);
            break;
        default:
            os = baos;
        }

        oos = new ObjectOutputStream(os);
        oos.writeObject(hash);
        if (os != null) {
            os.close();
        }
        baos.close();
        return baos.toByteArray();
    } catch (Exception ex) {
        ExHandler.handle(ex);
        return null;
    }
}

From source file:net.rptools.lib.io.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;//from   www .j ava  2s . co m

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    InputStream is = null;

    // Create the new file
    File newFile = new File(tmpDir, new GUID() + ".pak");
    ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
    try {
        saveTimer.start(CONTENT_FILE);
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            is = getFileAsInputStream(CONTENT_FILE); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop(CONTENT_FILE);

        saveTimer.start(PROPERTY_FILE);
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            xstream.toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop(PROPERTY_FILE);

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            is = getFileAsInputStream(path); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    //                  if (entry.getName().endsWith(".png") ||
                    //                        entry.getName().endsWith(".gif") ||
                    //                        entry.getName().endsWith(".jpeg"))
                    //                     zout.setLevel(Deflater.NO_COMPRESSION); // none needed for images as they are already compressed
                    //                  else
                    //                     zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
                    zout.putNextEntry(entry);
                    is = getFileAsInputStream(entry.getName()); // When copying, always use an InputStream
                    IOUtils.copy(is, zout);
                    IOUtils.closeQuietly(is);
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        IOUtils.closeQuietly(zout);
        zout = null;
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir, new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                saveTimer.start("backup file");
                FileUtil.copyFile(file, backupFile);
                file.delete();
                saveTimer.stop("backup file");
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file)) {
            saveTimer.start("backup newFile");
            FileUtil.copyFile(newFile, file);
            saveTimer.stop("backup newFile");
        }
        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zout);
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:com.joliciel.talismane.extensions.corpus.PosTaggerStatistics.java

@Override
public void onCompleteAnalysis() {
    try {//from w  w w  . j  a  v a2s . c o m
        if (writer != null) {
            PosTagSet posTagSet = talismaneSession.getPosTagSet();
            for (PosTag posTag : posTagSet.getTags()) {
                if (!posTagCounts.containsKey(posTag.getCode())) {
                    posTagCounts.put(posTag.getCode(), 0);
                }
            }

            double unknownLexiconPercent = 1;
            if (referenceWords != null) {
                int unknownLexiconCount = 0;
                for (String word : words) {
                    if (!referenceWords.contains(word))
                        unknownLexiconCount++;
                }
                unknownLexiconPercent = (double) unknownLexiconCount / (double) words.size();
            }
            double unknownLowercaseLexiconPercent = 1;
            if (referenceLowercaseWords != null) {
                int unknownLowercaseLexiconCount = 0;
                for (String lowercase : lowerCaseWords) {
                    if (!referenceLowercaseWords.contains(lowercase))
                        unknownLowercaseLexiconCount++;
                }
                unknownLowercaseLexiconPercent = (double) unknownLowercaseLexiconCount
                        / (double) lowerCaseWords.size();
            }

            writer.write(CSV.format("sentenceCount") + CSV.format(sentenceCount) + "\n");
            writer.write(CSV.format("sentenceLengthMean") + CSV.format(sentenceLengthStats.getMean()) + "\n");
            writer.write(CSV.format("sentenceLengthStdDev")
                    + CSV.format(sentenceLengthStats.getStandardDeviation()) + "\n");
            writer.write(CSV.format("lexiconSize") + CSV.format(words.size()) + "\n");
            writer.write(
                    CSV.format("lexiconUnknownInRefCorpus") + CSV.format(unknownLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("tokenCount") + CSV.format(tokenCount) + "\n");

            double unknownTokenPercent = ((double) unknownTokenCount / (double) tokenCount) * 100.0;
            writer.write(CSV.format("tokenUnknownInRefCorpus") + CSV.format(unknownTokenPercent) + "\n");

            double unknownInLexiconPercent = ((double) unknownInLexiconCount / (double) tokenCount) * 100.0;
            writer.write(CSV.format("tokenUnknownInRefLexicon") + CSV.format(unknownInLexiconPercent) + "\n");

            writer.write(CSV.format("lowercaseLexiconSize") + CSV.format(lowerCaseWords.size()) + "\n");
            writer.write(CSV.format("lowercaseLexiconUnknownInRefCorpus")
                    + CSV.format(unknownLowercaseLexiconPercent * 100.0) + "\n");
            writer.write(CSV.format("alphanumericCount") + CSV.format(alphanumericCount) + "\n");

            double unknownAlphanumericPercent = ((double) unknownAlphanumericCount / (double) alphanumericCount)
                    * 100.0;
            writer.write(CSV.format("alphaUnknownInRefCorpus") + CSV.format(unknownAlphanumericPercent) + "\n");

            double unknownAlphaInLexiconPercent = ((double) unknownAlphaInLexiconCount
                    / (double) alphanumericCount) * 100.0;
            writer.write(
                    CSV.format("alphaUnknownInRefLexicon") + CSV.format(unknownAlphaInLexiconPercent) + "\n");

            writer.write(CSV.format("openClassCount") + CSV.format(openClassCount) + "\n");

            double openClassUnknownPercent = ((double) openClassUnknownInRefCorpus / (double) openClassCount)
                    * 100.0;
            writer.write(
                    CSV.format("openClassUnknownInRefCorpus") + CSV.format(openClassUnknownPercent) + "\n");

            double openClassUnknownInLexiconPercent = ((double) openClassUnknownInLexicon
                    / (double) openClassCount) * 100.0;
            writer.write(CSV.format("openClassUnknownInRefLexicon")
                    + CSV.format(openClassUnknownInLexiconPercent) + "\n");

            writer.write(CSV.format("closedClassCount") + CSV.format(closedClassCount) + "\n");

            double closedClassUnknownPercent = ((double) closedClassUnknownInRefCorpus
                    / (double) closedClassCount) * 100.0;
            writer.write(
                    CSV.format("closedClassUnknownInRefCorpus") + CSV.format(closedClassUnknownPercent) + "\n");

            double closedClassUnknownInLexiconPercent = ((double) closedClassUnknownInLexicon
                    / (double) closedClassCount) * 100.0;
            writer.write(CSV.format("closedClassUnknownInRefLexicon")
                    + CSV.format(closedClassUnknownInLexiconPercent) + "\n");

            for (String posTag : posTagCounts.keySet()) {
                int count = posTagCounts.get(posTag);
                writer.write(CSV.format(posTag) + CSV.format(count)
                        + CSV.format(((double) count / (double) tokenCount) * 100.0) + "\n");
            }

            writer.flush();
            writer.close();
        }

        if (this.serializationFile != null) {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(serializationFile, false));
            zos.putNextEntry(new ZipEntry("Contents.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(this);
            } finally {
                oos.flush();
            }
            zos.flush();
            zos.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:cdr.forms.SwordDepositHandler.java

private File makeZipFile(gov.loc.mets.DocumentRoot metsDocumentRoot,
        IdentityHashMap<DepositFile, String> filenames) {

    // Get the METS XML

    String metsXml = serializeMets(metsDocumentRoot);

    // Create the zip file

    File zipFile;// w  ww. j a va 2s. c  o m

    try {
        zipFile = File.createTempFile("tmp", ".zip");
    } catch (IOException e) {
        throw new Error(e);
    }

    FileOutputStream fileOutput;

    try {
        fileOutput = new FileOutputStream(zipFile);
    } catch (FileNotFoundException e) {
        throw new Error(e);
    }

    ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

    try {

        ZipEntry entry;

        // Write the METS

        entry = new ZipEntry("mets.xml");
        zipOutput.putNextEntry(entry);

        PrintStream xmlPrintStream = new PrintStream(zipOutput);
        xmlPrintStream.print(metsXml);

        // Write files

        for (DepositFile file : filenames.keySet()) {

            if (!file.isExternal()) {

                entry = new ZipEntry(filenames.get(file));
                zipOutput.putNextEntry(entry);

                FileInputStream fileInput = new FileInputStream(file.getFile());

                byte[] buffer = new byte[1024];
                int length;

                while ((length = fileInput.read(buffer)) != -1)
                    zipOutput.write(buffer, 0, length);

                fileInput.close();

            }

        }

        zipOutput.finish();
        zipOutput.close();

        fileOutput.close();

    } catch (IOException e) {

        throw new Error(e);

    }

    return zipFile;

}

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

private InputStream createSampleZip() throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry("a/"));
    zipOutputStream.closeEntry();//from   w w w  .j a v a 2 s.co m
    zipOutputStream.putNextEntry(new ZipEntry("a/b.txt"));
    IOUtils.write("ab", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/"));
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/d.txt"));
    IOUtils.write("cd", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.close();
    return new ByteArrayInputStream(outputStream.toByteArray());
}

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   w w  w  .j a  v  a2 s  .  c  om
        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));
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceOneDirMultipleFiles() throws Exception {
    clearSourceDirectory();//from w  w w.j a  v a2 s.c om
    String buildSpecName = "buildspec.yml";
    String rootFileName = "pom.xml";
    String sourceDirName = "src";
    String srcFileName = "file.java";
    String srcFile2Name = "util.java";

    File buildSpec = new File("/tmp/source/" + buildSpecName);
    File rootFile = new File("/tmp/source/" + rootFileName);
    File sourceDir = new File("/tmp/source/" + sourceDirName);
    sourceDir.mkdir();
    File srcFile = new File("/tmp/source/src/" + srcFileName);
    File srcFile2 = new File("/tmp/source/src/" + srcFile2Name);

    String rootFileContents = "<plugin>codebuild</plugin>";
    String buildSpecContents = "Hello!!!!!";
    String srcFileContents = "int i = 1;";
    String srcFile2Contents = "util() { ; }";

    FileUtils.write(buildSpec, buildSpecContents);
    FileUtils.write(rootFile, rootFileContents);
    FileUtils.write(srcFile, srcFileContents);
    FileUtils.write(srcFile2, srcFile2Contents);

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    assertTrue(unzipFolder.list().length == 3);
    File srcFolder = new File("/tmp/folder/src/");
    assertTrue(srcFolder.list().length == 2);
    List<String> files = Arrays.asList(unzipFolder.list());
    assertTrue(files.contains(buildSpecName));
    assertTrue(files.contains(rootFileName));
    assertTrue(files.contains(sourceDirName));

    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    File extractedRootFile = new File(unzipFolder.getPath() + "/" + rootFileName);
    File extractedSrcFile = new File(unzipFolder.getPath() + "/src/" + srcFileName);
    File extractedSrcFile2 = new File(unzipFolder.getPath() + "/src/" + srcFile2Name);
    assertTrue(FileUtils.readFileToString(extractedBuildSpec).equals(buildSpecContents));
    assertTrue(FileUtils.readFileToString(extractedRootFile).equals(rootFileContents));
    assertTrue(FileUtils.readFileToString(extractedSrcFile).equals(srcFileContents));
    assertTrue(FileUtils.readFileToString(extractedSrcFile2).equals(srcFile2Contents));
}

From source file:cern.jarrace.controller.rest.controller.AgentContainerControllerTest.java

private File writeToZip(String entry, String data) throws IOException {
    File tmpFile = File.createTempFile("test", null);
    try (FileOutputStream fileOutput = new FileOutputStream(tmpFile);
            ZipOutputStream zipOutput = new ZipOutputStream(fileOutput)) {
        ZipEntry zipEntry = new JarEntry(entry);
        zipOutput.putNextEntry(zipEntry);
        zipOutput.write(data.getBytes());
    }/*from   w ww . j  a  v  a 2 s  . c o  m*/
    return tmpFile;
}

From source file:it.cnr.icar.eric.common.Utility.java

public static ZipOutputStream createZipOutputStream(String baseDir, String[] relativeFilePaths, OutputStream os)
        throws FileNotFoundException, IOException {
    if (baseDir.startsWith("file:/")) {
        baseDir = baseDir.substring(5);/*from  w  ww.j  a v  a2 s  .c  o m*/
    }
    ZipOutputStream zipoutputstream = new ZipOutputStream(os);

    zipoutputstream.setMethod(ZipOutputStream.STORED);

    for (int i = 0; i < relativeFilePaths.length; i++) {
        File file = new File(baseDir + FILE_SEPARATOR + relativeFilePaths[i]);

        byte[] buffer = new byte[1000];

        int n;

        FileInputStream fis;

        // Calculate the CRC-32 value.  This isn't strictly necessary
        //   for deflated entries, but it doesn't hurt.

        CRC32 crc32 = new CRC32();

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            crc32.update(buffer, 0, n);
        }

        fis.close();

        // Create a zip entry.

        ZipEntry zipEntry = new ZipEntry(relativeFilePaths[i]);

        zipEntry.setSize(file.length());
        zipEntry.setTime(file.lastModified());
        zipEntry.setCrc(crc32.getValue());

        // Add the zip entry and associated data.

        zipoutputstream.putNextEntry(zipEntry);

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            zipoutputstream.write(buffer, 0, n);
        }

        fis.close();

        zipoutputstream.closeEntry();
    }

    return zipoutputstream;
}