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.aurel.track.dbase.InitReportTemplateBL.java

/**
 * Unzip a ZIP file into a directory/*from   ww w  . java  2s  . c om*/
 * @param zipFile
 * @param dir
 */
private static void unzipFileIntoDirectory(ZipFile zipFile, File dir) {
    Enumeration files = zipFile.entries();
    File f = null;
    FileOutputStream fos = null;
    while (files.hasMoreElements()) {
        try {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            f = new File(dir.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            fos = new FileOutputStream(f);

            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            continue;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }
}

From source file:org.blockartistry.mod.Restructured.assets.ZipProcessor.java

private static void traverseZips(final File path, final Predicate<ZipEntry> test,
        final Predicate<Object[]> process) {

    for (final File file : getZipFiles(path)) {
        try {//from  w w  w.  ja  v a 2  s. c  o  m
            final ZipFile zip = new ZipFile(file);
            final String prefix = StringUtils.removeEnd(file.getName(), ".zip").toLowerCase().replaceAll("[-.]",
                    "_");
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                final ZipEntry entry = entries.nextElement();
                if (test.apply(entry)) {
                    final InputStream stream = zip.getInputStream(entry);
                    final String name = StringUtils.removeEnd(entry.getName(), ".schematic");
                    process.apply(new Object[] { prefix, name, stream });
                    stream.close();
                }
            }
            zip.close();
        } catch (final Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.apache.oozie.tools.OozieDBImportCLI.java

private static void checkDBVersion(EntityManager entityManager, ZipFile zipFile) throws IOException {
    try {/*from  w  w  w  .  j  av a2  s  .c  om*/
        String currentDBVersion = (String) entityManager
                .createNativeQuery("select data from OOZIE_SYS where name='db.version'").getSingleResult();
        String dumpDBVersion = null;
        ZipEntry entry = zipFile.getEntry(OOZIEDB_SYS_INFO_JSON);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
        String line;
        Gson gson = new Gson();
        while ((line = reader.readLine()) != null) {
            List<String> info = gson.fromJson(line, List.class);
            if (info.size() > 1 && "db.version".equals(info.get(0))) {
                dumpDBVersion = info.get(1);
            }
        }
        reader.close();
        if (currentDBVersion.equals(dumpDBVersion)) {
            System.out.println("Loading to Oozie database version " + currentDBVersion);
        } else {
            System.err.println("ERROR Oozie database version mismatch.");
            System.err.println("Oozie DB version:\t" + currentDBVersion);
            System.err.println("Dump DB version:\t" + dumpDBVersion);
            System.exit(1);
        }
    } catch (Exception e) {
        System.err.println();
        System.err.println("Error during DB version check: " + e.getMessage());
        System.err.println();
        System.err.println("Stack trace for the error was (for debug purposes):");
        System.err.println("--------------------------------------");
        e.printStackTrace(System.err);
        System.err.println("--------------------------------------");
        System.err.println();
    }
}

From source file:com.oneis.app.FileController.java

public static ZipFileExtractionResults zipFileExtraction(String zipFilePathname, String contentsDefault,
        String contentsRequested) throws IOException {
    ZipFileExtractionResults results = new ZipFileExtractionResults();

    ZipFile zipFile = new ZipFile(zipFilePathname);
    try {/*from  w  w  w.  ja  v a2s  .  c  om*/
        // Find the right entry, trying for the requested filename by defaulting back on the default given
        ZipEntry e = zipFile.getEntry(contentsRequested);
        results.chosenFile = contentsRequested;
        if (e == null) {
            e = zipFile.getEntry(contentsDefault);
            results.chosenFile = contentsDefault;
        }
        if (e == null) {
            return null;
        }

        results.data = IOUtils.toByteArray(zipFile.getInputStream(e));
    } finally {
        zipFile.close();
    }

    results.etagSuggestion = results.chosenFile.hashCode() & 0xfffff;

    return results;
}

From source file:org.codice.ddf.admin.application.service.impl.ApplicationFileInstaller.java

/**
 * Extracts all files/folders from the provided zip file to our location defined in
 * REPO_LOCATION./*from   w  w w. ja  v a 2s. com*/
 *
 * @param appZip
 *            the ZipFile to extract.
 * @return the detected feature file location.
 */
private static String installToRepo(ZipFile appZip) {
    String featureLocation = null;
    Enumeration<?> entries = appZip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry curEntry = (ZipEntry) entries.nextElement();
        if (!curEntry.isDirectory() && !curEntry.getName().startsWith("META-INF")) {
            try {
                InputStream is = appZip.getInputStream(curEntry);
                String outputName = curEntry.getName().substring("repository/".length());
                LOGGER.info("Writing out {}", curEntry.getName());
                org.apache.aries.util.io.IOUtils.writeOut(new File(REPO_LOCATION), outputName, is);
                if (isFeatureFile(curEntry)) {
                    featureLocation = outputName;
                }
            } catch (IOException e) {
                LOGGER.warn("Could not write out file.", e);
            }
        }
    }
    return featureLocation;
}

From source file:Main.java

public static String getJarSignature(String packagePath) throws IOException {
    Pattern signatureFilePattern = Pattern.compile("META-INF/[A-Z]+\\.SF");

    ZipFile packageZip = null;
    try {//from  ww w  . j a  v a2s  . c o m
        packageZip = new ZipFile(packagePath);
        // For each file in the zip.
        for (ZipEntry entry : Collections.list(packageZip.entries())) {
            // Ignore non-signature files.
            if (!signatureFilePattern.matcher(entry.getName()).matches()) {
                continue;
            }

            BufferedReader sigContents = null;
            try {
                sigContents = new BufferedReader(new InputStreamReader(packageZip.getInputStream(entry)));
                // For each line in the signature file.
                while (true) {
                    String line = sigContents.readLine();
                    if (line == null || line.equals("")) {
                        throw new IllegalArgumentException(
                                "Failed to find manifest digest in " + entry.getName());
                    }
                    String prefix = "SHA1-Digest-Manifest: ";
                    if (line.startsWith(prefix)) {
                        return line.substring(prefix.length());
                    }
                }
            } finally {
                if (sigContents != null) {
                    sigContents.close();
                }
            }
        }
    } finally {
        if (packageZip != null) {
            packageZip.close();
        }
    }

    throw new IllegalArgumentException("Failed to find signature file.");
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

private static void extractEntry(final ZipFile zf, final ZipEntry entry, final File destDir)
        throws IOException {
    File file = new File(destDir, entry.getName());

    if (entry.isDirectory()) {
        file.mkdirs();/*from w w w .j  a v  a  2  s.  c  o  m*/
    } else {
        new File(file.getParent()).mkdirs();

        try (InputStream is = zf.getInputStream(entry); FileOutputStream os = new FileOutputStream(file)) {
            copy(Channels.newChannel(is), os.getChannel());
        }
        // preserve modification time; must be set after the stream is closed
        file.setLastModified(entry.getTime());
    }
}

From source file:Main.java

public static void upZipFile(File zipFile, String folderPath) {
    ZipFile zf;
    try {// w ww.  j av a  2 s  .  c  o m
        zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            if (entry.isDirectory()) {
                String dirstr = entry.getName();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                File f = new File(dirstr);
                f.mkdir();
                continue;
            }

            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }

            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[BUFF_SIZE];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Extract a single named file from an archive.
 * /*w w w . j  a v a2  s. c  o m*/
 * @param needle Archive relative path of file to extract.
 * @param paleFile Experiment archive file.
 * @throws IOException
 * @throws ZipException
 */
public static byte[] extractJust(String needle, File paleFile) throws ZipException, IOException {
    ZipFile archive = new ZipFile(paleFile);
    try {
        ZipEntry ze = archive.getEntry(needle);
        if (ze == null) {
            throw new RuntimeException("Could not find experiment json in " + paleFile.getName());
        }
        InputStream in = archive.getInputStream(ze);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            copy(in, out);
            return out.toByteArray();
        } finally {
            in.close();
            out.close();
        }
    } finally {
        archive.close();
    }
}

From source file:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.//from  www.  j  ava 2s. c o m
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}