Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:msearch.filmlisten.MSFilmlisteSchreiben.java

private void xmlSchreibenStart(String datei) throws IOException, XMLStreamException {
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(947623049, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }//from   w  w w  . ja  v  a 2 s  . c  o  m
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    if (datei.endsWith(MSConst.FORMAT_BZ2)) {
        bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                9 /*Blocksize: 1 - 9*/);
        out = new OutputStreamWriter(bZip2CompressorOutputStream, MSConst.KODIERUNG_UTF);
    } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
        zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
        ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
        zipOutputStream.putNextEntry(entry);
        out = new OutputStreamWriter(zipOutputStream, MSConst.KODIERUNG_UTF);
    } else {
        out = new OutputStreamWriter(new FileOutputStream(file), MSConst.KODIERUNG_UTF);
    }
    writer = outFactory.createXMLStreamWriter(out);
    writer.writeStartDocument("UTF-8", "1.0");
    writer.writeCharacters("\n");//neue Zeile
    writer.writeStartElement(MSConst.XML_START);
    writer.writeCharacters("\n");//neue Zeile
}

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  va  2s  .c  o m
    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:abfab3d.shapejs.Project.java

public void save(String file) throws IOException {
    EvaluatedScript escript = m_script.getEvaluatedScript();
    Map<String, Parameter> scriptParams = escript.getParamMap();
    Gson gson = JSONParsing.getJSONParser();

    String code = escript.getCode();

    Path workingDirName = Files.createTempDirectory("saveScript");
    String workingDirPath = workingDirName.toAbsolutePath().toString();
    Map<String, Object> params = new HashMap<String, Object>();

    // Write the script to file
    File scriptFile = new File(workingDirPath + "/main.js");
    FileUtils.writeStringToFile(scriptFile, code, "UTF-8");

    // Loop through params and create key/pair entries
    for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) {
        String name = entry.getKey();
        Parameter pval = entry.getValue();

        if (pval.isDefaultValue())
            continue;

        ParameterType type = pval.getType();

        switch (type) {
        case URI:
            URIParameter urip = (URIParameter) pval;
            String u = (String) urip.getValue();

            //                   System.out.println("*** uri: " + u);
            File f = new File(u);

            String fileName = null;

            // TODO: This is hacky. If the parameter value is a directory, then assume it was
            //       originally a zip file, and its contents were extracted in the directory.
            //       Search for the zip file in the directory and copy that to the working dir.
            if (f.isDirectory()) {
                File[] files = f.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String fname = files[i].getName();
                    if (fname.endsWith(".zip")) {
                        fileName = fname;
                        f = files[i];/*from  w  w  w.  j a v a 2  s  .  co  m*/
                    }
                }
            } else {
                fileName = f.getName();
            }

            params.put(name, fileName);

            // Copy the file to working directory
            FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true);
            break;
        case LOCATION:
            LocationParameter lp = (LocationParameter) pval;
            Vector3d p = lp.getPoint();
            Vector3d n = lp.getNormal();
            double[] point = { p.x, p.y, p.z };
            double[] normal = { n.x, n.y, n.z };
            //                   System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal));
            Map<String, double[]> loc = new HashMap<String, double[]>();
            loc.put("point", point);
            loc.put("normal", normal);
            params.put(name, loc);
            break;
        case AXIS_ANGLE_4D:
            AxisAngle4dParameter aap = (AxisAngle4dParameter) pval;
            AxisAngle4d a = (AxisAngle4d) aap.getValue();
            params.put(name, a);
            break;
        case DOUBLE:
            DoubleParameter dp = (DoubleParameter) pval;
            Double d = (Double) dp.getValue();
            //                   System.out.println("*** double: " + d);

            params.put(name, d);
            break;
        case INTEGER:
            IntParameter ip = (IntParameter) pval;
            Integer i = ip.getValue();
            //                   System.out.println("*** int: " + pval);
            params.put(name, i);
            break;
        case STRING:
            StringParameter sp = (StringParameter) pval;
            String s = sp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, s);
            break;
        case COLOR:
            ColorParameter cp = (ColorParameter) pval;
            Color c = cp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, c.toHEX());
            break;
        case ENUM:
            EnumParameter ep = (EnumParameter) pval;
            String e = ep.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, e);
            break;
        default:
            params.put(name, pval);
        }

    }

    if (params.size() > 0) {
        String paramsJson = gson.toJson(params);
        File paramFile = new File(workingDirPath + "/" + "params.json");
        FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8");
    }

    File[] files = (new File(workingDirPath)).listFiles();

    FileOutputStream fos = new FileOutputStream(file);
    ZipOutputStream zos = new ZipOutputStream(fos);
    System.out.println("*** Num files to zip: " + files.length);

    try {
        byte[] buffer = new byte[1024];

        for (int i = 0; i < files.length; i++) {
            //                if (files[i].getName().endsWith(".zip")) continue;

            System.out.println("*** Adding file: " + files[i].getName());
            FileInputStream fis = new FileInputStream(files[i]);
            ZipEntry ze = new ZipEntry(files[i].getName());
            zos.putNextEntry(ze);

            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            fis.close();
        }
    } finally {
        zos.closeEntry();
        zos.close();
    }
}

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

/**
 * Write a list of files into a ZipOutputStream. The provided base path is
 * used to keep the structure defined by pFileList within the zip file.<BR/>
 * Due to the fact, that we have only one single base path, all files within
 * 'pFileList' must have in the same base directory. Adding files from a
 * higher level will cause unexpected zip entries.
 *
 * @param pFileList The list of input files
 * @param pBasePath The base path the will be removed from all file paths
 * before creating a new zip entry//from   w  w  w . j a v  a  2 s  .co  m
 * @param pZipOut The zip output stream
 * @throws IOException If something goes wrong, in most cases if there are
 * problems with reading the input files or writing into the output file
 */
private static void zip(File[] pFileList, String pBasePath, ZipOutputStream pZipOut) throws IOException {
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // Compress the files
        LOGGER.debug("Adding {} files to archive", pFileList.length);

        for (File pFileList1 : pFileList) {
            String entryName = pFileList1.getPath().replaceAll(Pattern.quote(pBasePath), "");
            if (entryName.startsWith(File.separator)) {
                entryName = entryName.substring(1);
            }

            if (pFileList1.isDirectory()) {
                LOGGER.debug("Adding directory entry");
                //add empty folders, too
                pZipOut.putNextEntry(new ZipEntry((entryName + File.separator).replaceAll("\\\\", "/")));
                pZipOut.closeEntry();
                File[] fileList = pFileList1.listFiles();
                if (fileList.length != 0) {
                    LOGGER.debug("Adding directory content recursively");
                    zip(fileList, pBasePath, pZipOut);
                } else {
                    LOGGER.debug("Skipping recursive call due to empty directory");
                }
                //should we close the entry here??
                //pZipOut.closeEntry();
            } else {
                LOGGER.debug("Adding file entry");
                try (final FileInputStream in = new FileInputStream(pFileList1)) {
                    // Add ZIP entry to output stream.
                    pZipOut.putNextEntry(new ZipEntry(entryName.replaceAll("\\\\", "/")));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        pZipOut.write(buf, 0, len);
                    }
                    // Complete the entry
                    LOGGER.debug("Closing file entry");
                    pZipOut.closeEntry();
                }
            }
        }
    } catch (IOException ioe) {
        LOGGER.error(
                "Aborting zip process due to an IOException caused by any zip stream (FileInput or ZipOutput)",
                ioe);
        throw ioe;
    } catch (RuntimeException e) {
        LOGGER.error("Aborting zip process due to an unexpected exception", e);
        throw new IOException("Unexpected exception during zip operation", e);
    }
}

From source file:com.nridge.core.base.std.FilUtl.java

/**
 * Compresses the input file into a ZIP file container.
 *
 * @param aInFileName The file name to be compressed.
 * @param aZipFileName The file name of the ZIP container.
 * @throws IOException Related to opening the file streams and
 * related read/write operations./*w ww.  j a  va2s  .com*/
 */
static public void zipFile(String aInFileName, String aZipFileName) throws IOException {
    File inFile;
    int byteCount;
    byte[] ioBuf;
    FileInputStream fileIn;
    ZipOutputStream zipOut;
    FileOutputStream fileOut;

    inFile = new File(aInFileName);
    if (inFile.isDirectory())
        return;

    ioBuf = new byte[FILE_IO_BUFFER_SIZE];
    fileIn = new FileInputStream(inFile);
    fileOut = new FileOutputStream(aZipFileName);
    zipOut = new ZipOutputStream(fileOut);
    zipOut.putNextEntry(new ZipEntry(inFile.getName()));
    byteCount = fileIn.read(ioBuf);
    while (byteCount > 0) {
        zipOut.write(ioBuf, 0, byteCount);
        byteCount = fileIn.read(ioBuf);
    }
    fileIn.close();
    zipOut.closeEntry();
    zipOut.close();
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * API to zip list of files to a desired file. Operation aborted if any file is invalid or a directory.
 * /*  w ww .  j  av a 2  s. c  om*/
 * @param filePaths {@link List}< {@link String}>
 * @param outputFilePath {@link String}
 * @throws IOException in case of error
 */
public static void zipMultipleFiles(List<String> filePaths, String outputFilePath) throws IOException {
    LOGGER.info("Zipping files to " + outputFilePath + ".zip file");
    File outputFile = new File(outputFilePath);

    if (outputFile.exists()) {
        LOGGER.info(outputFilePath + " file already exists. Deleting existing and creating a new file.");
        outputFile.delete();
    }

    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;
    ZipOutputStream out = null;
    FileInputStream input = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(outputFilePath));
        for (String filePath : filePaths) {
            LOGGER.info("Writing file " + filePath + " into zip file.");

            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                throw new Exception("Invalid file: " + file.getAbsolutePath()
                        + ". Either file does not exists or it is a directory.");
            }
            input = new FileInputStream(file); // Stream to read file
            ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            bytesRead = input.read(buffer);
            while (bytesRead != -1) {
                out.write(buffer, 0, bytesRead);
                bytesRead = input.read(buffer);
            }

        }

    } catch (Exception e) {
        LOGGER.error("Exception occured while zipping file." + e.getMessage(), e);
    } finally {
        if (input != null) {
            input.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/** creates a plugin .zip and returns the url for testing */
private String createPlugin(final Path structure, String... properties) throws IOException {
    writeProperties(structure, properties);
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override/*w  w w  .  j  av a 2s .c  om*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                stream.putNextEntry(new ZipEntry(structure.relativize(file).toString()));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    if (randomBoolean()) {
        writeSha1(zip, false);
    } else if (randomBoolean()) {
        writeMd5(zip, false);
    }
    return zip.toUri().toURL().toString();
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerFactoryConfigurationError, TransformerException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream());
    ZipEntry zipEntry;//from w  ww  . j a va2 s  . c  om
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        LOG.debug("copy ZIP entry: " + zipEntry.getName());
        ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
        zipOutputStream.putNextEntry(newZipEntry);
        if ("[Content_Types].xml".equals(zipEntry.getName())) {
            Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            Element typesElement = contentTypesDocument.getDocumentElement();

            /*
             * We need to add an Override element.
             */
            Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override");
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName);
            overrideElement.setAttribute("ContentType",
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml");
            typesElement.appendChild(overrideElement);

            Element nsElement = contentTypesDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/content-types");
            NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                /*
                 * Add Default element for 'sigs' extension.
                 */
                Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default");
                defaultElement.setAttribute("Extension", "sigs");
                defaultElement.setAttribute("ContentType",
                        "application/vnd.openxmlformats-package.digital-signature-origin");
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) {
            Document relsDocument = loadDocumentNoClose(zipInputStream);

            Element nsElement = relsDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/relationships");
            NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                Element relationshipElement = relsDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString());
                relationshipElement.setAttribute("Type",
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin");
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs");

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) {
            hasOriginSigsRels = true;
            Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            Element relationshipElement = originSignRelsDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
            String relationshipId = "rel-" + UUID.randomUUID().toString();
            relationshipElement.setAttribute("Id", relationshipId);
            relationshipElement.setAttribute("Type",
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature");
            String target = FilenameUtils.getName(signatureZipEntryName);
            LOG.debug("target: " + target);
            relationshipElement.setAttribute("Target", target);
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (false == hasOriginSigsRels) {
        /*
         * Add signature relationships document.
         */
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    /*
     * Return.
     */
    zipInputStream.close();
    return zipOutputStream;
}

From source file:com.ibm.liberty.starter.ProjectZipConstructor.java

public void createZipFromMap(ZipOutputStream zos) throws IOException {
    System.out.println("Entering method ProjectZipConstructor.createZipFromMap()");
    Enumeration<String> en = fileMap.keys();
    while (en.hasMoreElements()) {
        String path = en.nextElement();
        byte[] byteArray = fileMap.get(path);
        ZipEntry entry = new ZipEntry(path);
        entry.setSize(byteArray.length);
        entry.setCompressedSize(-1);/*w w  w .  ja  v  a  2 s .  c  o m*/
        try {
            zos.putNextEntry(entry);
            zos.write(byteArray);
        } catch (IOException e) {
            throw new IOException(e);
        }
    }
}

From source file:ZipTransformTest.java

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

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

        // Transform the ZIP file
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file1);
            out = new FileOutputStream(file2);

            ZipUtil.transformEntry(in, name, new FileZipEntryTransformer() {
                protected void transform(ZipEntry zipEntry, File in, File out) throws IOException {
                    FileWriter fw = new FileWriter(out);
                    fw.write("CAFEBABE");
                    fw.close();
                }
            }, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

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