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:net.rptools.lib.io.PackedFile.java

/**
 * Returns an InputStream that corresponds to the zip file path specified. This method should be called only for
 * binary file contents such as images (assets and thumbnails). For character-based data, use
 * {@link #getFileAsReader(String)} instead.
 * //from w  w  w.j a va  2 s.c  om
 * @param path
 *            zip file archive path entry
 * @return InputStream representing the data stream
 * @throws IOException
 */
public InputStream getFileAsInputStream(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.getFileAsInputStream(explodedFile);

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

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * Method that will be called to process the summary collection file. The upload process will unpack the zipped collection of summary files and then
 * decrypt them.//from  w w w.j a  va2s.co m
 *
 * @throws Exception
 */
protected void processSummaries() throws Exception {
    String zipFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ZIP), ".");
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");

    File file = new File(TaskUtils.getZippedOutputPath(), zipFilename);
    OutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String zipEntryName = zipEntry.getName();
        if (!zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)
                && !zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            int count;
            byte[] data = new byte[TaskConstants.BUFFER_SIZE];
            CipherInputStream zipCipherInputStream = new CipherInputStream(
                    encryptedFile.getInputStream(zipEntry), cipher);
            while ((count = zipCipherInputStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
                outStream.write(data, 0, count);
            }
            zipCipherInputStream.close();
        }
    }
    outStream.close();

    File outputPath = TaskUtils.getSummaryOutputPath();
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = zipEntries.nextElement();
        processedFilename = zipEntry.getName();
        File f = new File(outputPath, zipEntry.getName());
        // ensure that the parent path exists
        File parent = f.getParentFile();
        if (parent.exists() || parent.mkdirs()) {
            FileCopyUtils.copy(zipFile.getInputStream(zipEntry),
                    new BufferedOutputStream(new FileOutputStream(f)));
        }
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.TextCorpus.java

/**
 * @return list of files in corpus/*from   w  ww .  j a v  a 2 s. co m*/
 * @throws IOException 
 * @throws ZipException 
 */
@SuppressWarnings("unchecked")
protected HashMap<URI, InputStream> getEntries() throws Exception {

    HashMap<URI, InputStream> entries = new HashMap<URI, InputStream>();

    if (corpusFileMediaType == MediaType.ZIP) {
        ZipFile zippedCorpusDir = new ZipFile(corpus);
        Enumeration<? extends ZipEntry> zipEntries = zippedCorpusDir.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            if (!zipEntry.isDirectory()) {

                String uriValue = corpus.toURI().toString() + "/";
                String entryName = zipEntry.getName();
                uriValue += URLEncoder.encode(entryName, "utf-8");

                entries.put(new URI(uriValue), zippedCorpusDir.getInputStream(zipEntry));
            }
        }
    } else if (corpusFileMediaType == MediaType.DIRECTORY) {
        for (File f : corpus.listFiles()) {
            entries.put(f.toURI(), new FileInputStream(f));
        }
    }

    return entries;
}

From source file:net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl.java

/**
 * @see net.sourceforge.squirrel_sql.fw.util.IOUtilities# copyResourceFromJarFile(java.lang.String,
 *      java.lang.String, java.lang.String)
 *//*from w ww .j  ava2 s  . c  om*/
@Override
public void copyResourceFromJarFile(String jarFilename, String resourceName, String destinationFile)
        throws ZipException, IOException {
    ZipFile appJar = new ZipFile(new File(jarFilename));
    Enumeration<? extends ZipEntry> entries = appJar.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.endsWith(resourceName)) {
            InputStream is = null;
            try {
                FileWrapper destinationFileWrapper = fileWrapperFactory.create(destinationFile);
                is = appJar.getInputStream(entry);
                copyBytesToFile(is, destinationFileWrapper);
            } finally {
                closeInputStream(is);
            }
            break;
        }
    }

}

From source file:net.rptools.lib.io.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.
 * /*from w  ww  . j  a va2s  .  c  o m*/
 * @param path
 *            zip file archive path entry
 * @return Reader representing the data stream
 * @throws IOException
 */
public LineNumberReader 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 new LineNumberReader(FileUtil.getFileAsReader(explodedFile));

    ZipEntry entry = new ZipEntry(path);
    ZipFile zipFile = getZipFile();
    InputStream in = null;
    try {
        in = new BufferedInputStream(zipFile.getInputStream(entry));
        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 LineNumberReader(new InputStreamReader(in, "UTF-8"));
    } catch (IOException ex) {
        // Don't need to close 'in' since zipFile.close() will do so
        throw ex;
    }
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Unzips the supplied zip file//from w  w  w  .j  a v a  2 s .  co  m
 * 
 * @param zip
 *            The zip file to extract
 * @param destinationDir
 *            the directory to extract the zip to
 * @throws IOException
 *             if an error occurred while extracting the zip file.
 */
public static void extractZipFile(File zip, File destinationDir) throws IOException {
    if (!zip.exists()) {
        throw new IllegalArgumentException("zip file does not exist");
    }

    if (!zip.isFile()) {
        throw new IllegalArgumentException("supplied zip file is not a file");
    }

    if (!destinationDir.exists()) {
        throw new IllegalArgumentException("destination does not exist");
    }

    if (!destinationDir.isDirectory()) {
        throw new IllegalArgumentException("destination is not a directory");
    }

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

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        String entryName = entry.getName();

        File fileForEntry = new File(destinationDir, entryName);
        if (entry.isDirectory() && !fileForEntry.exists()) {
            fileForEntry.mkdirs();
        } else {
            InputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            FileUtils.copyInputStreamToFile(is, fileForEntry);
        }
    }
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final ZipFile zipFile, final File destFolder) throws IOException {
    for (Enumeration en = zipFile.entries(); en.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) en.nextElement();
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }//from   www .  j  a  va 2 s. c o  m
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                InputStream in = zipFile.getInputStream(entry);
                try {
                    IoUtil.copyStream(in, out, 1024);
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
    }
}

From source file:apim.restful.importexport.utils.APIImportUtil.java

/**
 * This method decompresses API the archive
 *
 * @param sourceFile  The archive containing the API
 * @param destination location of the archive to be extracted
 * @return Name of the extracted directory
 * @throws APIImportException If the decompressing fails
 *//*from w  ww. ja  v  a2  s.c o  m*/
public static String extractArchive(File sourceFile, String destination) throws APIImportException {

    BufferedInputStream inputStream = null;
    InputStream zipInputStream = null;
    FileOutputStream outputStream = null;
    ZipFile zip = null;
    String archiveName = null;

    try {
        zip = new ZipFile(sourceFile);
        Enumeration zipFileEntries = zip.entries();
        int index = 0;

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {

            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            //This index variable is used to get the extracted folder name; that is root directory
            if (index == 0) {
                archiveName = currentEntry.substring(0,
                        currentEntry.indexOf(APIImportExportConstants.ARCHIVE_PATH_SEPARATOR));
                --index;
            }

            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();

            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.info("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }

            if (!entry.isDirectory()) {
                zipInputStream = zip.getInputStream(entry);
                inputStream = new BufferedInputStream(zipInputStream);

                // write the current file to the destination
                outputStream = new FileOutputStream(destinationFile);
                IOUtils.copy(inputStream, outputStream);
            }
        }
        return archiveName;
    } catch (IOException e) {
        log.error("Failed to extract archive file ", e);
        throw new APIImportException("Failed to extract archive file. " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

public Properties searchForVersionProperties() {
    try {/*  www  . j av  a2 s  .  c  om*/
        FMLLog.log(getModId(), Level.DEBUG,
                "Attempting to load the file version.properties from %s to locate a version number for %s",
                getSource().getName(), getModId());
        Properties version = null;
        if (getSource().isFile()) {
            ZipFile source = new ZipFile(getSource());
            ZipEntry versionFile = source.getEntry("version.properties");
            if (versionFile != null) {
                version = new Properties();
                version.load(source.getInputStream(versionFile));
            }
            source.close();
        } else if (getSource().isDirectory()) {
            File propsFile = new File(getSource(), "version.properties");
            if (propsFile.exists() && propsFile.isFile()) {
                version = new Properties();
                FileInputStream fis = new FileInputStream(propsFile);
                version.load(fis);
                fis.close();
            }
        }
        return version;
    } catch (Exception e) {
        Throwables.propagateIfPossible(e);
        FMLLog.log(getModId(), Level.TRACE, "Failed to find a usable version.properties file");
        return null;
    }
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * Loads the juror models used for consensus.
 * @param options specific options to use when loading the model
 * @throws IOException if there is a problem accessing the model
 * @throws ClassNotFoundException if the type of the model is not recognized
 *//*from   w w  w. jav  a 2  s  . c o m*/
private void loadJurorModels(final DAVOptions options) throws IOException, ClassNotFoundException {
    jurorModels.clear();

    final String pathToModel = FilenameUtils.getFullPath(modelFilename);
    final String endpointName = FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(pathToModel));

    if (properties.getBoolean("bdval.consensus.jurors.embedded", false)) {
        final File tmpdir = File.createTempFile("juror-models", "");
        tmpdir.delete();
        tmpdir.mkdir();

        try {
            // load juror models from the zip file
            final ZipFile zipFile = new ZipFile(zipFilename);
            for (final String jurorPrefix : jurorModelFilenamePrefixes) {
                // zip files should always use "/" as a separator
                final String jurorFilename = "models/" + endpointName + "/" + jurorPrefix + ".zip";
                LOG.debug("Loading juror model " + jurorFilename);
                final InputStream jurorStream = zipFile.getInputStream(zipFile.getEntry(jurorFilename));

                final File jurorFile = new File(FilenameUtils.concat(tmpdir.getPath(), jurorFilename));

                // put the juror model to disk so it can be loaded with existing code
                IOUtils.copy(jurorStream, FileUtils.openOutputStream(jurorFile));

                final BDVModel jurorModel = new BDVModel(jurorFile.getPath());
                jurorModel.load(options);
                jurorModels.add(jurorModel);
            }
        } finally {
            FileUtils.forceDeleteOnExit(tmpdir);
        }
    } else {
        // load juror models from disk
        final File finalModelPath = new File(pathToModel);
        final File finalModelParentPath = new File(finalModelPath.getParent());
        // assume the model is under a directory "models" at the same level as a models
        // directory which contains the model components.
        for (final String jurorPrefix : jurorModelFilenamePrefixes) {
            final String modelComponentFilename = finalModelParentPath.getParent() + SystemUtils.FILE_SEPARATOR
                    + "models" + SystemUtils.FILE_SEPARATOR + endpointName + SystemUtils.FILE_SEPARATOR
                    + jurorPrefix;
            LOG.debug("Loading model component " + modelComponentFilename);
            final BDVModel jurorModel = new BDVModel(modelComponentFilename);
            jurorModel.load(options);
            jurorModels.add(jurorModel);
        }
    }

    if (jurorModels.size() < 1) {
        throw new IllegalStateException("No juror models could be found");
    }

    jurorModelsAreLoaded = true;
}