Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.xclinical.mdr.server.impexp.ZipResourceResolver.java

public ZipResourceResolver(InputStream stm) throws IOException {
    File file = File.createTempFile("mdrres", ".tmp");
    FileOutputStream out = new FileOutputStream(file);
    Streams.copy(stm, out, true);//from  ww w. j av  a2  s.  c  om
    this.file = new ZipFile(file);
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

public void unzipArchive(File archive, File outputDir) throws IOException {
    try {/*w w  w .ja v a 2 s.  co m*/
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            unzipEntry(zipfile, entry, outputDir);
        }
    } catch (Exception e) {
        throw new IOException("Error while extracting file " + archive, e);
    }
}

From source file:it.geosolutions.geofence.gui.server.utility.IoUtility.java

/**
 * Decompress./*from   www. j a  v  a2  s .  c om*/
 *
 * @param prefix
 *            the prefix
 * @param inputFile
 *            the input file
 * @param tempFile
 *            the temp file
 * @return the file
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static File decompress(final String prefix, final File inputFile, final File tempFile)
        throws IOException {
    final File tmpDestDir = createTodayPrefixedDirectory(prefix, new File(tempFile.getParent()));

    ZipFile zipFile = new ZipFile(inputFile);

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {

        ZipEntry entry = (ZipEntry) entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);

        if (entry.isDirectory()) {
            // Assume directories are stored parents first then
            // children.
            (new File(tmpDestDir, entry.getName())).mkdir();

            continue;
        }

        File newFile = new File(tmpDestDir, entry.getName());

        FileOutputStream fos = new FileOutputStream(newFile);
        try {
            byte[] buf = new byte[1024];
            int len;

            while ((len = stream.read(buf)) >= 0) {
                saveCompressedStream(buf, fos, len);
            }

        } catch (IOException e) {
            zipFile.close();

            IOException ioe = new IOException("Not valid ZIP archive file type.");
            ioe.initCause(e);
            throw ioe;
        } finally {
            fos.flush();
            fos.close();

            stream.close();
        }
    }
    zipFile.close();

    if ((tmpDestDir.listFiles().length == 1) && (tmpDestDir.listFiles()[0].isDirectory())) {
        return getShpFile(tmpDestDir.listFiles()[0]);
    }

    // File[] files = tmpDestDir.listFiles(new FilenameFilter() {
    //
    // public boolean accept(File dir, String name) {
    // return FilenameUtils.getExtension(name).equalsIgnoreCase("shp");
    // }
    // });
    //
    // return files.length > 0 ? files[0] : null;

    return getShpFile(tmpDestDir);
}

From source file:com.splout.db.common.CompressorUtil.java

public static void uncompress(File file, File dest) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(dest, entry.getName());
        entryDestination.getParentFile().mkdirs();
        InputStream in = zipFile.getInputStream(entry);
        OutputStream out = new FileOutputStream(entryDestination);
        IOUtils.copy(in, out);/* ww w. j a va  2  s .  co  m*/
        in.close();
        out.close();
    }
}

From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPaths.java

private void ExtractStructuralFeaturesInMemory(String filePath, Map<String, Integer> structuralPaths) {
    String path;//  ww w  .j ava2s  .  co m
    String directoryPath;
    String fileExtension;
    try {
        ZipFile zipFile = new ZipFile(filePath);

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            path = entry.getName();
            directoryPath = FilenameUtils.getFullPath(path);
            fileExtension = FilenameUtils.getExtension(path);

            AddStructuralPath(directoryPath, structuralPaths);
            AddStructuralPath(path, structuralPaths);

            if (fileExtension.equals("rels") || fileExtension.equals("xml")) {
                AddXMLStructuralPaths(zipFile.getInputStream(entry), path, structuralPaths);
            }
        }
    } catch (IOException ex) {
        Console.PrintException(
                String.format("Error extracting OOXML structural features from file: %s", filePath), ex);
    }
}

From source file:edu.harvard.i2b2.PreProcessFhirSpec.java

public PreProcessFhirSpec() throws IOException, XQueryUtilException {
    logger.trace("hi");
    ArrayList<String> resourceList = new ArrayList<String>();
    resourceList.add("Patient".toLowerCase());
    resourceList.add("Medication".toLowerCase());
    resourceList.add("MedicationStatement".toLowerCase());
    resourceList.add("Observation".toLowerCase());
    ZipFile zipFile = new ZipFile(Utils.getFilePath("fhir-spec.zip"));// fhir-all-xsd.zip
    logger.trace("" + zipFile.getName());

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    for (String rName : resourceList) {
        String fName = "site/" + rName + ".profile.xml";
        logger.trace("" + zipFile.getEntry(fName));
        String fContent = IOUtils.toString(zipFile.getInputStream(zipFile.getEntry(fName)));
        logger.trace("" + XQueryUtil.processXQuery(
                "declare default element namespace \"http://hl7.org/fhir\";//searchParam", fContent));

    }/*  ww  w.ja  va 2s.  c  om*/

    /*while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       if(!entry.getName().matches(".*\\.html$")) continue;
       Pattern p = Pattern.compile("^site/([^\\.\\\\]*)\\..*$");
       Matcher m = p.matcher(entry.getName());
       String rname="";
       if (m.matches()) {
    //logger.trace("" + entry.getName() + "->" + m.group(1));
    rname=m.group(1).toLowerCase();
       }
               
       if (resourceList.contains(rname))
    logger.trace(entry.getName()+"->" + rname);
       // InputStream stream = zipFile.getInputStream(entry);
               
    }*/

}

From source file:net.chris54721.infinitycubed.utils.Utils.java

public static void unzip(File zipFile, File outputFolder) {
    InputStream in = null;/*from   ww  w .  j  a v a2  s  . c o  m*/
    OutputStream out = null;
    try {
        ZipFile zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        if (!outputFolder.isDirectory())
            outputFolder.mkdirs();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryTarget = new File(outputFolder, entry.getName());
            entryTarget.getParentFile().mkdirs();
            if (entry.isDirectory())
                entryTarget.mkdirs();
            else {
                in = zip.getInputStream(entry);
                out = new FileOutputStream(entryTarget);
                IOUtils.copy(in, out);
            }
        }
    } catch (Exception e) {
        LogHelper.error("Failed extracting " + zipFile.getName(), e);
    } finally {
        if (in != null)
            IOUtils.closeQuietly(in);
        if (out != null)
            IOUtils.closeQuietly(out);
    }
}

From source file:asciidoc.maven.plugin.AbstractAsciiDocMojo.java

/**
 * No-arg constructor./*from   www  .j a  v  a 2s .c o  m*/
 */
public AbstractAsciiDocMojo() {
    try {
        File jarFile = new File(AbstractAsciiDocMojo.class.getProtectionDomain().getCodeSource().getLocation()
                .toURI().getPath());
        if (getLog().isDebugEnabled())
            getLog().debug("sourceJarFile: " + jarFile.getAbsolutePath());
        if (asciiDocHome == null) {
            ZipEntry zipEntry = null;
            String zipEntryName = null;
            ZipFile jarZipFile = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> e = jarZipFile.entries();
            while (e.hasMoreElements()) {
                zipEntry = (ZipEntry) e.nextElement();
                zipEntryName = zipEntry.getName();
                if (zipEntryName.startsWith("asciidoc") && zipEntryName.endsWith(".zip")) {
                    if (getLog().isInfoEnabled())
                        getLog().info("Found AsciiDoc in " + zipEntryName);
                    asciiDocHome = new File(jarFile.getParent(), FilenameUtils.removeExtension(zipEntryName));
                    break;
                }
            }
            if (asciiDocHome != null && !asciiDocHome.exists()) {
                unzipEntry(jarZipFile, zipEntry, jarFile.getParentFile());
                File asciiDocArchive = new File(jarFile.getParent(), zipEntryName);
                unzipArchive(asciiDocArchive, jarFile.getParentFile());
                asciiDocArchive.deleteOnExit();
            }
            if (getLog().isInfoEnabled())
                getLog().info("asciiDocHome: " + asciiDocHome);
        }
    } catch (URISyntaxException use) {
        getLog().error(use.getMessage(), use);
        // don't throw use;
    } catch (ZipException ze) {
        getLog().error(ze.getMessage(), ze);
        // don't throw ze;
    } catch (IOException ioe) {
        getLog().error(ioe.getMessage(), ioe);
        // don't throw ioe;
    }
}

From source file:com.jivesoftware.os.routing.bird.endpoints.base.LocateStringResource.java

String getStringResource() {
    Map<String, Long> htSizes = new HashMap<>();
    try {/*from  ww w.j ava 2s.  co  m*/
        try (final ZipFile zf = new ZipFile(jarFileName)) {
            Enumeration<? extends ZipEntry> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = e.nextElement();
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                htSizes.put(ze.getName(), ze.getSize());
            }
        }
        // extract resources and put them into the hashtable.
        FileInputStream fis = new FileInputStream(jarFileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        try (final ZipInputStream zis = new ZipInputStream(bis)) {
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                if (ze.isDirectory()) {
                    continue;
                }
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1) {
                    size = htSizes.get(ze.getName()).intValue();
                }
                byte[] b = new byte[size];
                int rb = 0;
                int chunk = 0;
                while ((size - rb) > 0) {
                    chunk = zis.read(b, rb, size - rb);
                    if (chunk == -1) {
                        break;
                    }
                    rb += chunk;
                }
                InputStream inputStream = new ByteArrayInputStream(b);
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");
                return writer.toString();
            }
        }
    } catch (Exception e) {
        LOG.warn("Failed to locate " + resourceName, e);
    }
    return null;
}

From source file:Main.java

public static void unzip(String strZipFile) {

    try {/*from www  . j  a  v a 2s  .  c  om*/
        /*
         * STEP 1 : Create directory with the name of the zip file
         * 
         * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries
         */
        File fSourceZip = new File(strZipFile);
        String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
        File temp = new File(zipPath);
        temp.mkdir();
        System.out.println(zipPath + " created");

        /*
         * STEP 2 : Extract entries while creating required sub-directories
         */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());

            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();

            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                // System.out.println("Extracting " + destinationFilePath);

                /*
                 * Get the InputStream for current entry of the zip file using
                 * 
                 * InputStream getInputStream(Entry entry) method.
                 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

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

                /*
                 * read the current entry from the zip file, extract it and write the extracted file.
                 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }

                // flush the output stream and close it.
                bos.flush();
                bos.close();

                // close the input stream.
                bis.close();
            }

        }
        zipFile.close();
    } catch (IOException ioe) {
        System.out.println("IOError :" + ioe);
    }

}