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:com.mgmtp.jfunk.data.source.ArchiveDataSource.java

private Map<String, DataSet> getDataSets() {
    if (dataSets == null) {
        String archiveFileName = configuration.get("dataSource." + getName() + ".archiveFileName");
        if (archiveFileName == null) {
            throw new IllegalStateException("No archive files configured.");
        }//www .j  ava 2s.co m
        log.info("Using " + archiveFileName);

        dataSets = newHashMap();
        try {
            ZipFile zip = new ZipFile(archiveFileName);
            for (Enumeration<? extends ZipEntry> zipEntryEnum = zip.entries(); zipEntryEnum
                    .hasMoreElements();) {
                ZipEntry zipEntry = zipEntryEnum.nextElement();
                String name = zipEntry.getName();
                Matcher matcher = KEY_PATTERN.matcher(name);
                if (matcher.find()) {
                    InputStream is = null;
                    try {
                        is = zip.getInputStream(zipEntry);
                        String key = matcher.group(1);
                        ExtendedProperties props = new ExtendedProperties();
                        props.load(is);
                        log.debug("Adding data for key=" + key);
                        dataSets.put(key, new DefaultDataSet(props));
                    } finally {
                        closeQuietly(is);
                    }
                }
            }
        } catch (IOException ex) {
            throw new JFunkException("Error getting data sets.", ex);
        }
    }
    return dataSets;
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;/* w w w  . j a  va 2  s  . c o m*/
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

From source file:org.geowe.server.upload.FileUploadZipServlet.java

private String readZipFile(ZipFile zipFile) {
    String content = EMPTY;//  ww w.j a  va 2  s.  c om

    try {

        Enumeration<?> enu = zipFile.entries();
        if (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            if (zipEntry.isDirectory()) {
                content = BAD_FORMAT;
            } else if (!(zipEntry.getName().equals(PRJ_FILE_NAME))) {
                content = BAD_FORMAT;
            } else {
                InputStream is = zipFile.getInputStream(zipEntry);
                content = new java.util.Scanner(is).useDelimiter("\\A").next();
            }

            // String name = zipEntry.getName();
            // long size = zipEntry.getSize();
            // long compressedSize = zipEntry.getCompressedSize();
            // LOG.info("name: " + name + " | size: " + size
            // + " | compressed size: " + compressedSize);

        }
        zipFile.close();

    } catch (IOException e) {
        LOG.error("Se produce error en ZipFile: " + e.getMessage());
        e.printStackTrace();
    }

    return content;
}

From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java

private Reader getDescriptorReader(ZipFile zipFile, String descriptor) throws IOException {
    ZipEntry entry = searchEntry(zipFile, descriptor);

    if (entry == null) {
        return null;
    }/*from w  w  w.j  a  va  2s.  c  o m*/

    InputStream is = zipFile.getInputStream(entry);

    if (is == null) {
        throw new IOException("The " + descriptor + " descriptor cannot be read in " + zipFile.getName() + ".");
    }

    return ReaderFactory.newReader(is, ReaderFactory.UTF_8);
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid.//from ww  w .jav a  2s . c o  m
 *
 * @param file The zip file
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(String file) throws IOException {
    ZipFile zip = null;
    TriangleMesh[] ret_val = null;

    try {
        zip = new ZipFile(file);

        ZipEntry entry = zip.getEntry("manifest.xml");
        if (entry == null) {
            throw new IOException("Cannot find manifest.xml in top level");
        }

        InputStream is = zip.getInputStream(entry);
        mf = parseManifest(is);

        if (mf == null) {
            throw new IOException("Could not parse manifest file");
        }

        List<STSPart> plist = mf.getParts();
        int len = plist.size();

        ret_val = new TriangleMesh[len];
        for (int i = 0; i < len; i++) {
            STSPart part = plist.get(i);
            ZipEntry ze = zip.getEntry(part.getFile());
            MeshReader reader = new MeshReader(zip.getInputStream(ze), "",
                    FilenameUtils.getExtension(part.getFile()));
            IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
            reader.getTriangles(its);

            // TODO: in this case we could return a less heavy triangle mesh struct?
            WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
            ret_val[i] = mesh;
        }

        return ret_val;
    } finally {
        if (zip != null)
            zip.close();
    }
}

From source file:com.shazam.fork.io.ClassesDexFileExtractor.java

private void dumpDexFilesFromApk(File apkFile, File outputFolder) {
    ZipFile zip = null;
    InputStream classesDexInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {/*w  w  w .  java2 s .  c  om*/
        zip = new ZipFile(apkFile);
        int index = 1;
        String currentDex;
        while (true) {
            currentDex = CLASSES_PREFIX + (index > 1 ? index : "") + DEX_EXTENSION;
            ZipEntry classesDex = zip.getEntry(currentDex);
            if (classesDex != null) {
                File dexFileDestination = new File(outputFolder, currentDex);
                classesDexInputStream = zip.getInputStream(classesDex);
                fileOutputStream = new FileOutputStream(dexFileDestination);
                copyLarge(classesDexInputStream, fileOutputStream);
                index++;
            } else {
                break;
            }
        }
    } catch (IOException e) {
        throw new DexFileExtractionException(
                "Error when trying to scan " + apkFile.getAbsolutePath() + " for test classes.", e);
    } finally {
        closeQuietly(classesDexInputStream);
        closeQuietly(fileOutputStream);
        closeQuietly(zip);
    }
}

From source file:asciidoc.maven.plugin.tools.ZipHelper.java

public void unzipEntry(ZipFile zipfile, ZipEntry zipEntry, File outputDir) throws IOException {
    if (zipEntry.isDirectory()) {
        createDir(new File(outputDir, zipEntry.getName()));
        return;/*from ww w.j  a va2  s.  c om*/
    }
    File outputFile = new File(outputDir, zipEntry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    if (this.log.isDebugEnabled())
        this.log.debug("Extracting " + zipEntry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(zipEntry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }

    if ((outputFile != null)
            && (!outputFile.isDirectory() && FileHelper.getFileExtension(outputFile).equalsIgnoreCase("py"))) {
        outputFile.setExecutable(true);
    }
}

From source file:org.jboss.tools.tycho.sitegenerator.FetchSourcesFromManifests.java

static public void unzipToDirectory(File file, String newPath) throws ZipException, IOException {
    int BUFFER = 2048;
    ZipFile zip = new ZipFile(file);
    (new File(newPath)).mkdirs();
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        File destFile = new File(newPath, currentEntry);
        File destinationParent = destFile.getParentFile();
        // create the parent directory structure if needed
        destinationParent.mkdirs();//from w  w w  .  ja  v a 2s  . c  o  m
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            // read and write until last byte is encountered
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zip.close();
}

From source file:eu.diversify.disco.experiments.testing.Tester.java

private void unzipDistribution(String archiveName) throws IOException {
    String fileName = escape(archiveName);
    ZipFile zipFile = new ZipFile(fileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
            File entryDestination = new File("target/", entry.getName());
            entryDestination.getParentFile().mkdirs();
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);//from   ww w.  j ava  2 s.c o  m
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:ch.jamiete.hilda.plugins.PluginManager.java

/**
 * Attempts to load plugin data from the {@code plugin.json} file.
 * @param file/*www .j av  a2s  .  c o m*/
 * @return the plugin data or {@code null} if no data could be loaded
 * @throws IllegalArgumentException if any of the conditions of a plugin data file are not met
 */
private PluginData loadPluginData(final File file) {
    PluginData data = null;

    try {
        final ZipFile zipFile = new ZipFile(file);
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final InputStream stream = zipFile.getInputStream(entry);

            if (entry.getName().equals("plugin.json")) {
                data = new Gson().fromJson(IOUtils.toString(stream, Charset.defaultCharset()),
                        PluginData.class);

                Sanity.nullCheck(data.name, "A plugin must define its name.");
                Sanity.nullCheck(data.mainClass, "A plugin must define its main class.");
                Sanity.nullCheck(data.version, "A plugin must define its version.");
                Sanity.nullCheck(data.author, "A plugin must define its author.");

                data.pluginFile = file;

                if (data.dependencies == null) {
                    data.dependencies = new String[0];
                }
            }
        }

        zipFile.close();
    } catch (final Exception ex) {
        Hilda.getLogger().log(Level.SEVERE,
                "Encountered exception when trying to load plugin JSON for " + file.getName(), ex);
    }

    return data;
}