Example usage for java.util.zip ZipFile getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.apache.jackrabbit.j2ee.BackwardsCompatibilityIT.java

private void unpack(File archive, File dir) throws IOException {
    ZipFile zip = new ZipFile(archive);
    try {/*from w w  w.  ja  v a 2 s.c om*/
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith("META-INF")) {
            } else if (entry.isDirectory()) {
                new File(dir, entry.getName()).mkdirs();
            } else {
                File file = new File(dir, entry.getName());
                file.getParentFile().mkdirs();
                InputStream input = zip.getInputStream(entry);
                try {
                    OutputStream output = new FileOutputStream(file);
                    try {
                        IOUtils.copy(input, output);
                    } finally {
                        output.close();
                    }
                } finally {
                    input.close();
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:com.flexive.tests.disttools.DistPackageTest.java

/**
 * Extracts the flexive-dist.zip package and returns the (temporary) directory handle. All extracted
 * files will be registered for deletion on the JVM exit.
 *
 * @return  the (temporary) directory handle.
 * @throws IOException  if the package could not be extracted
 *///  w  ww . j  av  a 2 s.c om
private File extractDistPackage() throws IOException {
    final ZipFile file = getDistFile();
    final File tempDir = createTempDir();
    try {
        final Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry zipEntry = entries.nextElement();
            final String path = getTempPath(tempDir, zipEntry);
            if (zipEntry.isDirectory()) {
                final File dir = new File(path);
                dir.mkdirs();
                dir.deleteOnExit();
            } else {
                final InputStream in = file.getInputStream(zipEntry);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(path));
                // copy streams
                final byte[] buffer = new byte[32768];
                int len;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                new File(path).deleteOnExit();
            }
        }
    } finally {
        file.close();
    }
    return new File(tempDir + File.separator + "flexive-dist");
}

From source file:com.google.appinventor.buildserver.ProjectBuilder.java

private ArrayList<String> extractProjectFiles(ZipFile inputZip, File projectRoot) throws IOException {
    ArrayList<String> projectFileNames = Lists.newArrayList();
    Enumeration<? extends ZipEntry> inputZipEnumeration = inputZip.entries();
    while (inputZipEnumeration.hasMoreElements()) {
        ZipEntry zipEntry = inputZipEnumeration.nextElement();
        final InputStream extractedInputStream = inputZip.getInputStream(zipEntry);
        File extractedFile = new File(projectRoot, zipEntry.getName());
        LOG.info("extracting " + extractedFile.getAbsolutePath() + " from input zip");
        Files.createParentDirs(extractedFile); // Do I need this?
        Files.copy(new InputSupplier<InputStream>() {
            public InputStream getInput() throws IOException {
                return extractedInputStream;
            }//  w  w w  . j  a v a  2s  .  c o  m
        }, extractedFile);
        projectFileNames.add(extractedFile.getPath());
    }
    return projectFileNames;
}

From source file:org.eclipse.emf.ecp.emf2web.wizard.ViewModelExportWizard.java

/**
 * Extracts the given zip file to the given destination.
 *
 * @param zipFilePath/*from  w  w w .java2s. c om*/
 *            The absolute path of the zip file.
 * @param destinationPath
 *            The absolute path of the destination directory;
 * @throws IOException when extracting or copying fails.
 */
private void extractZip(String zipFilePath, String destinationPath) throws IOException {
    final ZipFile zipFile = new ZipFile(zipFilePath);
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final File entryDestination = new File(destinationPath, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            final InputStream in = zipFile.getInputStream(entry);
            final OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
    zipFile.close();
}

From source file:com.cloudant.sync.datastore.DatastoreSchemaTests.java

@SuppressWarnings("ResultOfMethodCallIgnored") // mkdirs result should be fine
private boolean unzipToDirectory(File zipPath, File outputDirectory) {
    try {//from   www. j  av  a2 s  .c om

        ZipFile zipFile = new ZipFile(zipPath);
        try {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(outputDirectory, entry.getName());
                if (entry.isDirectory())
                    entryDestination.mkdirs();
                else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    out.close();
                }
            }
        } finally {
            zipFile.close();
        }

        return true;

    } catch (Exception ex) {
        return false;
    }
}

From source file:com.t3.persistence.PackedFile.java

/**
 * Returns an InputStreamReader that corresponds to the zip file path specified.
 * This method should be called only for character-based file contents such as
 * the <b>CONTENT_FILE</b> and <b>PROPERTY_FILE</b>.  For binary
 * data, such as images (assets and thumbnails) use {@link #getFileAsInputStream(String)}
 * instead.//www .  j  av  a 2 s.  c o  m
 * 
 * @param path zip file archive path entry
 * @return Reader representing the data stream
 * @throws IOException
 */
public Reader getFileAsReader(String path) throws IOException {
    File explodedFile = getExplodedFile(path);
    if ((!file.exists() && !tmpFile.exists() && !explodedFile.exists()) || removedFileSet.contains(path))
        throw new FileNotFoundException(path);
    if (explodedFile.exists())
        return FileUtil.getFileAsReader(explodedFile);

    ZipEntry entry = new ZipEntry(path);
    ZipFile zipFile = getZipFile();
    InputStream in = null;
    try {
        in = new BufferedInputStream(zipFile.getInputStream(entry));
        if (in != null) {
            if (log.isDebugEnabled()) {
                String type;
                type = FileUtil.getContentType(in);
                if (type == null)
                    type = FileUtil.getContentType(explodedFile);
                log.debug("FileUtil.getContentType() returned " + (type != null ? type : "(null)"));
            }
            return new InputStreamReader(in);
        }
    } catch (Exception ex) {
        // Don't need to close 'in' since zipFile.close() will do so
    }
    throw new FileNotFoundException(path);
}

From source file:io.github.jeremgamer.preview.actions.Launch.java

private void extractNatives() throws IOException {
    for (String s : NATIVE_JARS) {
        File archive = new File(s);
        ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(VANILLA_NATIVE_DIR.replaceAll("<version>", "1.8.1"),
                    entry.getName());//from   w  w w.j  a  va 2  s .c o  m
            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                in.close();
                out.close();
            }
        }
        zipFile.close();
    }
}

From source file:com.s2g.pst.resume.importer.UnZipHelper.java

/**
 * Unzip it//w ww.  jav a 2 s  . co  m
 *
 * @param fileName
 * @param outputFolder
 *
 * @throws java.io.FileNotFoundException
 */
public void unZipFolder(String fileName, String outputFolder) throws IOException {

    ZipFile zipFile = new ZipFile(fileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(outputFolder, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            //FileHelper fileHelper = new FileHelper();
            //String filename = fileHelper.getUniqueFileName(outputFolder, FilenameUtils.removeExtension(entry.getName()));
            //System.out.println("zip :" + filename);
            //new File(filename).mkdirs();

            entryDestination.mkdirs();

        } else {
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    zipFile.close();
    this.deleteZipFile(fileName);
    System.out.println("Done");

}

From source file:org.ecoinformatics.seek.datasource.EcogridZippedDataCacheItem.java

/**
 * This method overwirtes the super class. It is specified to unzip a zip
 * file//from  w w  w  .  ja  v a  2  s .c  o  m
 * 
 * @throws Exception
 */
public void unCompressCacheItem() throws Exception {
    if (unCompressedCacheItemDir != null) {
        log.debug("At unCompressCacheItem method in Zip ojbect");
        ZipFile zipFile = new ZipFile(getAbsoluteFileName());
        Enumeration enu = zipFile.entries();
        // go though every zip entry
        byte[] array = new byte[300 * 1024];
        while (enu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) enu.nextElement();
            // write zipEntry to a local file in
            // Cachedir/unzip/mlocatFilename/
            String name = entry.getName();
            if (name != null) {
                log.debug("Zip entry name is " + name);
                File unzipFile = new File(unCompressedCacheItemDir, name);
                FileOutputStream fileWriter = new FileOutputStream(unzipFile);
                InputStream fileReader = zipFile.getInputStream(entry);
                int len;
                while ((len = fileReader.read(array)) >= 0) {
                    fileWriter.write(array, 0, len);
                }
                fileReader.close();
                fileWriter.close();
            }
        }
        unCompressedFileList = unCompressedCacheItemDir.list();
    }

}

From source file:de.uni_koeln.spinfo.maalr.services.admin.shared.DataLoader.java

public void createFromSQLDump(File file, int maxEntries)
        throws IOException, NoDatabaseAvailableException, InvalidEntryException, IndexException {

    if (!file.exists()) {
        logger.info("No data to import - file " + file + " does not exist.");
        return;/*from w w  w . j  a  v  a2  s . c o m*/
    }

    BufferedReader br;
    ZipFile zipFile = null;
    if (file.getName().endsWith(".zip")) {
        logger.info("Trying to read data from zip file=" + file.getName());
        zipFile = new ZipFile(file);
        String entryName = file.getName().replaceAll(".zip", "");
        //         ZipEntry entry = zipFile.getEntry(entryName+".tsv");
        ZipEntry entry = zipFile.getEntry(entryName);
        if (entry == null) {
            logger.info("No file named " + entryName + " found in zip file - skipping import");
            zipFile.close();
            return;
        }
        br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
    } else {
        logger.info("Trying to read data from file " + file);
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    }

    String line = br.readLine();
    String[] keys = line.split("\t", -1);
    Database db = Database.getInstance();
    List<DBObject> entries = new ArrayList<DBObject>();
    int counter = 0;
    String userId = loginManager.getCurrentUserId();
    while ((line = br.readLine()) != null) {
        String[] values = line.split("\t", -1);
        if (values.length != keys.length) {
            logger.warn("Ignoring entry: Attribute mismatch (" + values.length + " entries found, "
                    + keys.length + " entries expected) in line " + line);
            continue;
        }
        LemmaVersion version = new LemmaVersion();
        for (int i = 0; i < keys.length; i++) {
            String value = values[i].trim();
            String key = keys[i].trim();
            if (value.length() == 0)
                continue;
            if (key.length() == 0)
                continue;
            version.setValue(key, value);
        }
        LexEntry entry = new LexEntry(version);
        entry.setCurrent(version);
        entry.getCurrent().setStatus(Status.NEW_ENTRY);
        entry.getCurrent().setVerification(Verification.ACCEPTED);
        long timestamp = System.currentTimeMillis();
        String embeddedTimeStamp = version.getEntryValue(LemmaVersion.TIMESTAMP);
        if (embeddedTimeStamp != null) {
            timestamp = Long.parseLong(embeddedTimeStamp);
            version.removeEntryValue(LemmaVersion.TIMESTAMP);
        }
        entry.getCurrent().setUserId(userId);
        entry.getCurrent().setTimestamp(timestamp);
        entry.getCurrent().setCreatorRole(Role.ADMIN_5);
        entries.add(Converter.convertLexEntry(entry));
        if (entries.size() == 10000) {
            db.insertBatch(entries);
            entries.clear();
        }
        counter++;
        if (counter == maxEntries) {
            logger.warn("Skipping db creation, as max entries is " + maxEntries);
            break;
        }
    }
    db.insertBatch(entries);
    entries.clear();
    //loginManager.login("admin", "admin");
    Iterator<LexEntry> iterator = db.getEntries();
    index.dropIndex();
    index.addToIndex(iterator);
    logger.info("Index has been created, swapping to RAM...");
    index.reloadIndex();
    logger.info("RAM-Index updated.");
    br.close();
    if (zipFile != null) {
        zipFile.close();
    }
    //loginManager.logout();
    logger.info("Dataloader initialized.");
}