java.util.zip.ZipFile

Here are the examples of the java api class java.util.zip.ZipFile taken from open source projects.

1. FileUtil#archiveContainsEntry()

Project: servicemix-utils
File: FileUtil.java
/**
     * Validate that an archive contains a named entry
     * 
     * @param theFile
     * @param name
     * @return true if the entry exists
     * @throws IOException
     */
public static boolean archiveContainsEntry(File theFile, String name) throws IOException {
    boolean result = false;
    ZipFile zipFile;
    zipFile = new ZipFile(theFile);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements(); ) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        if (entry.getName().equals(name)) {
            result = true;
            break;
        }
    }
    zipFile.close();
    return result;
}

2. DirectoryBrowserSupportTest#zipDownload()

Project: Jenkins2
File: DirectoryBrowserSupportTest.java
@Issue("JENKINS-19752")
@Test
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());
    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);
    ZipFile readzip = new ZipFile(zipfile);
    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));
    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);
    is.close();
    readzip.close();
    zipfile.delete();
}

3. ZipEntryTest#testMaxLengthComment()

Project: j2objc
File: ZipEntryTest.java
public void testMaxLengthComment() throws Exception {
    String maxLengthComment = makeString(65535, "z");
    File f = createTemporaryZipFile();
    ZipOutputStream out = createZipOutputStream(f);
    ZipEntry ze = new ZipEntry("x");
    ze.setComment(maxLengthComment);
    out.putNextEntry(ze);
    out.closeEntry();
    out.close();
    // Read it back, and check that we see the entry.
    ZipFile zipFile = new ZipFile(f);
    assertEquals(maxLengthComment, zipFile.getEntry("x").getComment());
    zipFile.close();
}

4. ZipEntryTest#testMaxLengthExtra()

Project: j2objc
File: ZipEntryTest.java
public void testMaxLengthExtra() throws Exception {
    byte[] maxLengthExtra = new byte[65535];
    File f = createTemporaryZipFile();
    ZipOutputStream out = createZipOutputStream(f);
    ZipEntry ze = new ZipEntry("x");
    ze.setSize(0);
    ze.setExtra(maxLengthExtra);
    out.putNextEntry(ze);
    out.closeEntry();
    out.close();
    // Read it back, and check that we see the entry.
    ZipFile zipFile = new ZipFile(f);
    assertEquals(maxLengthExtra.length, zipFile.getEntry("x").getExtra().length);
    zipFile.close();
}

5. ZipEntryTest#testMaxLengthName()

Project: j2objc
File: ZipEntryTest.java
public void testMaxLengthName() throws Exception {
    String maxLengthName = makeString(65535, "z");
    File f = createTemporaryZipFile();
    ZipOutputStream out = createZipOutputStream(f);
    out.putNextEntry(new ZipEntry(maxLengthName));
    out.closeEntry();
    out.close();
    // Read it back, and check that we see the entry.
    ZipFile zipFile = new ZipFile(f);
    assertNotNull(zipFile.getEntry(maxLengthName));
    zipFile.close();
}

6. AbstractZipFileTest#testZipFileWithLotsOfEntries()

Project: j2objc
File: AbstractZipFileTest.java
public void testZipFileWithLotsOfEntries() throws IOException {
    int expectedEntryCount = 64 * 1024 - 1;
    final File f = createTemporaryZipFile();
    writeEntries(createZipOutputStream(f), expectedEntryCount, 0, false);
    ZipFile zipFile = new ZipFile(f);
    int entryCount = 0;
    for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); ) {
        ZipEntry zipEntry = e.nextElement();
        ++entryCount;
    }
    assertEquals(expectedEntryCount, entryCount);
    zipFile.close();
}

7. UpdateableZipTest#testRemoveEntry()

Project: intellij-community
File: UpdateableZipTest.java
public void testRemoveEntry() throws Exception {
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    jbZip.getEntry("/second").erase();
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry removedEntry = utilZip.getEntry("/second");
    assertNull(removedEntry);
    utilZip.close();
}

8. UpdateableZipTest#testReplaceEntryContent()

Project: intellij-community
File: UpdateableZipTest.java
public void testReplaceEntryContent() throws Exception {
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    JBZipEntry newEntry = jbZip.getOrCreateEntry("/second");
    newEntry.setData("Content Replaced".getBytes());
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry updatedEntry = utilZip.getEntry("/second");
    assertNotNull(updatedEntry);
    String thirdText = FileUtil.loadTextAndClose(new InputStreamReader(utilZip.getInputStream(updatedEntry)));
    assertEquals("Content Replaced", thirdText);
    utilZip.close();
}

9. UpdateableZipTest#testAppendEntry()

Project: intellij-community
File: UpdateableZipTest.java
public void testAppendEntry() throws Exception {
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    JBZipEntry newEntry = jbZip.getOrCreateEntry("/third");
    newEntry.setData("third".getBytes());
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry thirdEntry = utilZip.getEntry("/third");
    assertNotNull(thirdEntry);
    String thirdText = FileUtil.loadTextAndClose(new InputStreamReader(utilZip.getInputStream(thirdEntry)));
    assertEquals("third", thirdText);
    utilZip.close();
}

10. DirectoryBrowserSupportTest#zipDownload()

Project: hudson
File: DirectoryBrowserSupportTest.java
@Issue("JENKINS-19752")
@Test
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());
    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);
    ZipFile readzip = new ZipFile(zipfile);
    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));
    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);
    is.close();
    readzip.close();
    zipfile.delete();
}

11. LanguageRegistry#searchZipForLanguages()

Project: FML
File: LanguageRegistry.java
private void searchZipForLanguages(File source, Side side) throws IOException {
    ZipFile zf = new ZipFile(source);
    for (ZipEntry ze : Collections.list(zf.entries())) {
        Matcher matcher = assetENUSLang.matcher(ze.getName());
        if (matcher.matches()) {
            String lang = matcher.group(2);
            FMLLog.fine("Injecting found translation data for lang %s in zip file %s at %s into language system", lang, source.getName(), ze.getName());
            LanguageRegistry.instance().injectLanguage(lang, StringTranslate.parseLangFile(zf.getInputStream(ze)));
            // Ensure en_US is available to StringTranslate on the server
            if ("en_US".equals(lang) && side == Side.SERVER) {
                StringTranslate.inject(zf.getInputStream(ze));
            }
        }
    }
    zf.close();
}

12. ClassPathResource#listJarURL()

Project: erjang
File: ClassPathResource.java
private static void listJarURL(Set<String> res, URL url) throws IOException {
    String path = url.getPath();
    int bang = path.indexOf('!');
    String jar = path.substring("file:".length(), bang);
    String elm = path.substring(bang + 2);
    ZipFile z = new ZipFile(jar);
    Enumeration<? extends ZipEntry> ents = z.entries();
    while (ents.hasMoreElements()) {
        ZipEntry ent = ents.nextElement();
        if (ent.getName().startsWith(elm)) {
            add(res, elm, ent.getName());
        }
    }
    z.close();
}

13. Main#openInputFileAsZip()

Project: dex-method-counts
File: Main.java
/**
     * Tries to open an input file as a Zip archive (jar/apk) with a
     * "classes.dex" inside.
     */
void openInputFileAsZip(String fileName, List<RandomAccessFile> dexFiles) throws IOException {
    ZipFile zipFile;
    // Try it as a zip file.
    try {
        zipFile = new ZipFile(fileName);
    } catch (FileNotFoundException fnfe) {
        System.err.println("Unable to open '" + fileName + "': " + fnfe.getMessage());
        throw fnfe;
    } catch (ZipException ze) {
        return;
    }
    // Open and add all files matching "classes.*\.dex" in the zip file.
    for (ZipEntry entry : Collections.list(zipFile.entries())) {
        if (entry.getName().matches("classes.*\\.dex")) {
            dexFiles.add(openDexFile(zipFile, entry));
        }
    }
    zipFile.close();
}

14. UpdateableZipTest#testRemoveEntry()

Project: consulo
File: UpdateableZipTest.java
public void testRemoveEntry() throws Exception {
    File zipFile = createTestUtilZip();
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    jbZip.getEntry("/second").erase();
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry removedEntry = utilZip.getEntry("/second");
    assertNull(removedEntry);
    utilZip.close();
}

15. UpdateableZipTest#testReplaceEntryContent()

Project: consulo
File: UpdateableZipTest.java
public void testReplaceEntryContent() throws Exception {
    File zipFile = createTestUtilZip();
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    JBZipEntry newEntry = jbZip.getOrCreateEntry("/second");
    newEntry.setData("Content Replaced".getBytes());
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry updatedEntry = utilZip.getEntry("/second");
    assertNotNull(updatedEntry);
    String thirdText = FileUtil.loadTextAndClose(new InputStreamReader(utilZip.getInputStream(updatedEntry)));
    assertEquals("Content Replaced", thirdText);
    utilZip.close();
}

16. UpdateableZipTest#testAppendEntry()

Project: consulo
File: UpdateableZipTest.java
public void testAppendEntry() throws Exception {
    File zipFile = createTestUtilZip();
    JBZipFile jbZip = new JBZipFile(zipFile);
    assertEntryWithContentExists(jbZip, "/first", "first");
    assertEntryWithContentExists(jbZip, "/second", "second");
    JBZipEntry newEntry = jbZip.getOrCreateEntry("/third");
    newEntry.setData("third".getBytes());
    jbZip.close();
    ZipFile utilZip = new ZipFile(zipFile);
    ZipEntry thirdEntry = utilZip.getEntry("/third");
    assertNotNull(thirdEntry);
    String thirdText = FileUtil.loadTextAndClose(new InputStreamReader(utilZip.getInputStream(thirdEntry)));
    assertEquals("third", thirdText);
    utilZip.close();
}

17. CustomModelImportTest#testNotZipFileUpload()

Project: community-edition
File: CustomModelImportTest.java
public void testNotZipFileUpload() throws Exception {
    File file = getResourceFile("validModel.zip");
    ZipFile zipFile = new ZipFile(file);
    ZipEntry zipEntry = zipFile.entries().nextElement();
    File unzippedModelFile = TempFileProvider.createTempFile(zipFile.getInputStream(zipEntry), "validModel", ".xml");
    tempFiles.add(unzippedModelFile);
    zipFile.close();
    PostRequest postRequest = buildMultipartPostRequest(unzippedModelFile);
    // CMM upload supports only zip file.
    sendRequest(postRequest, 400);
}

18. ZipUtil#entryEquals()

Project: zt-zip
File: ZipUtil.java
/**
   * Compares two ZIP entries (byte-by-byte). .
   *
   * @param f1
   *          first ZIP file.
   * @param f2
   *          second ZIP file.
   * @param path1
   *          name of the first entry.
   * @param path2
   *          name of the second entry.
   * @return <code>true</code> if the contents of the entries were same.
   */
public static boolean entryEquals(File f1, File f2, String path1, String path2) {
    ZipFile zf1 = null;
    ZipFile zf2 = null;
    try {
        zf1 = new ZipFile(f1);
        zf2 = new ZipFile(f2);
        return doEntryEquals(zf1, zf2, path1, path2);
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf1);
        closeQuietly(zf2);
    }
}

19. TestCollector#testCollectFilesonYearBoundary()

Project: voltdb
File: TestCollector.java
@Test
public void testCollectFilesonYearBoundary() throws Exception {
    createLogFiles();
    //set reference date to be 1st January of the current year
    Calendar cal = Calendar.getInstance();
    cal.set(cal.get(Calendar.YEAR), 0, 01);
    Collector.m_currentTimeMillis = cal.getTimeInMillis();
    resetCurrentTime = false;
    ZipFile collectionZip = collect(voltDbRootPath, true, 4);
    int logCount = 0;
    Enumeration<? extends ZipEntry> e = collectionZip.entries();
    while (e.hasMoreElements()) {
        if (e.nextElement().getName().startsWith(rootDir + File.separator + "voltdb_logs" + File.separator))
            logCount++;
    }
    assertEquals(logCount, 1);
    resetCurrentTime = true;
    collectionZip.close();
}

20. TestCollector#testDaysToCollectOption()

Project: voltdb
File: TestCollector.java
@Test
public void testDaysToCollectOption() throws Exception {
    createLogFiles();
    ZipFile collectionZip = collect(voltDbRootPath, true, 3);
    int logCount = 0;
    Enumeration<? extends ZipEntry> e = collectionZip.entries();
    while (e.hasMoreElements()) {
        ZipEntry z = e.nextElement();
        if (z.getName().startsWith(rootDir + File.separator + "voltdb_logs" + File.separator))
            logCount++;
    }
    assertEquals(logCount, 4);
    collectionZip.close();
}

21. TestCollector#testJvmCrash()

Project: voltdb
File: TestCollector.java
@Test
public void testJvmCrash() throws Exception {
    Thread.sleep(STARTUP_DELAY);
    try {
        client.callProcedure("CrashJVM");
    } catch (Exception e) {
    }
    client.close();
    cluster.shutDown();
    ZipFile collectionZip = collect(voltDbRootPath, true, 50);
    int pid = getpid(voltDbRootPath);
    String workingDir = getWorkingDir(voltDbRootPath);
    File jvmCrashGenerated = new File(workingDir, "hs_err_pid" + pid + ".log");
    jvmCrashGenerated.deleteOnExit();
    ZipEntry logFile = collectionZip.getEntry(rootDir + File.separator + "system_logs" + File.separator + "hs_err_pid" + pid + ".log");
    assertNotNull(logFile);
    collectionZip.close();
}

22. ZipsTest#testOverwritingTimestamps()

Project: zt-zip
File: ZipsTest.java
public void testOverwritingTimestamps() throws IOException {
    File src = new File(MainExamplesTest.DEMO_ZIP);
    File dest = File.createTempFile("temp", ".zip");
    final ZipFile zf = new ZipFile(src);
    try {
        Zips.get(src).addEntries(new ZipEntrySource[0]).destination(dest).process();
        Zips.get(dest).iterate(new ZipEntryCallback() {

            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                String name = zipEntry.getName();
                // original timestamp is believed to be earlier than test execution time.
                assertTrue("Timestamps were carried over for entry " + name, zf.getEntry(name).getTime() < zipEntry.getTime());
            }
        });
    } finally {
        ZipUtil.closeQuietly(zf);
        FileUtils.deleteQuietly(dest);
    }
}

23. UmlautTest#testZipFileGetEntriesWithCharset()

Project: zt-zip
File: UmlautTest.java
public void testZipFileGetEntriesWithCharset() throws Exception {
    if (ignoreTestIfJava6()) {
        return;
    }
    ZipFile zf = ZipFileUtil.getZipFile(file, Charset.forName("UTF8"));
    Enumeration entries = zf.entries();
    while (entries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) entries.nextElement();
        assertTrue(ze.getName(), fileContents.contains(ze.getName()));
    }
}

24. UnpackEntryExample#usual()

Project: zt-zip
File: UnpackEntryExample.java
public static void usual() throws IOException {
    byte[] bytes = null;
    ZipFile zf = new ZipFile("demo.zip");
    try {
        ZipEntry ze = zf.getEntry("foo.txt");
        if (ze != null) {
            InputStream is = zf.getInputStream(ze);
            try {
                bytes = IOUtils.toByteArray(is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } finally {
        zf.close();
    }
    System.out.println("Read " + bytes.length + " bytes.");
}

25. ZipUtil#unpackEntry()

Project: zt-zip
File: ZipUtil.java
/**
   * Unpacks a single file from a ZIP archive to a file.
   *
   * @param zip
   *          ZIP file.
   * @param name
   *          entry name.
   * @param file
   *          target file to be created or overwritten.
   * @return <code>true</code> if the entry was found and unpacked,
   *         <code>false</code> if the entry was not found.
   */
public static boolean unpackEntry(File zip, String name, File file) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(zip);
        return doUnpackEntry(zf, name, file);
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf);
    }
}

26. ZipUtil#unpackEntry()

Project: zt-zip
File: ZipUtil.java
/**
   * Unpacks a single entry from a ZIP file.
   *
   * @param zip
   *          ZIP file.
   * @param name
   *          entry name.
   * @return contents of the entry or <code>null</code> if it was not found.
   */
public static byte[] unpackEntry(File zip, String name) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(zip);
        return doUnpackEntry(zf, name);
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf);
    }
}

27. ZipUtil#containsAnyEntry()

Project: zt-zip
File: ZipUtil.java
/**
   * Checks if the ZIP file contains any of the given entries.
   *
   * @param zip
   *          ZIP file.
   * @param names
   *          entry names.
   * @return <code>true</code> if the ZIP file contains any of the given
   *         entries.
   */
public static boolean containsAnyEntry(File zip, String[] names) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(zip);
        for (int i = 0; i < names.length; i++) {
            if (zf.getEntry(names[i]) != null) {
                return true;
            }
        }
        return false;
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf);
    }
}

28. ZipUtil#getCompressionLevelOfEntry()

Project: zt-zip
File: ZipUtil.java
/**
   * Returns the compression level of a given entry of the ZIP file.
   *
   * @param zip
   *          ZIP file.
   * @param name
   *          entry name.
   * @return Returns <code>ZipEntry.STORED</code>, <code>ZipEntry.DEFLATED</code> or -1 if
   * the ZIP file does not contain the given entry.
   */
public static int getCompressionLevelOfEntry(File zip, String name) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(zip);
        ZipEntry zipEntry = zf.getEntry(name);
        if (zipEntry == null) {
            return -1;
        }
        return zipEntry.getMethod();
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf);
    }
}

29. ZipUtil#containsEntry()

Project: zt-zip
File: ZipUtil.java
/* Extracting single entries from ZIP files. */
/**
   * Checks if the ZIP file contains the given entry.
   *
   * @param zip
   *          ZIP file.
   * @param name
   *          entry name.
   * @return <code>true</code> if the ZIP file contains the given entry.
   */
public static boolean containsEntry(File zip, String name) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(zip);
        return zf.getEntry(name) != null;
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        closeQuietly(zf);
    }
}

30. TestCollector#testRepeatFileName()

Project: voltdb
File: TestCollector.java
@Test
public void testRepeatFileName() throws Exception {
    createLogFiles();
    ZipFile collectionZip = collect(voltDbRootPath, true, 3);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    ZipEntry repeatFile = collectionZip.getEntry(rootDir + File.separator + "voltdb_logs" + File.separator + "volt-junit-fulllog.txt." + formatter.format(new Date()) + "(1)");
    assertNotNull(repeatFile);
}

31. ZipUtils#extract()

Project: uPortal
File: ZipUtils.java
public static void extract(File archive, File outputDir) throws IOException {
    final ZipFile zipfile = new ZipFile(archive);
    for (final Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements(); ) {
        final ZipEntry entry = e.nextElement();
        final File outputFile = checkDirectories(entry, outputDir);
        if (outputFile != null) {
            final InputStream is = zipfile.getInputStream(entry);
            try {
                writeFile(is, outputFile);
            } finally {
                is.close();
            }
        }
    }
}

32. ProcessRealAndroidJar#findAllClazzesIn()

Project: unmock-plugin
File: ProcessRealAndroidJar.java
private static ArrayList<String> findAllClazzesIn(String file) throws IOException {
    ArrayList<String> res = new ArrayList<String>();
    ZipFile f = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = f.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.getName().endsWith(".class")) {
            res.add(entry.getName().replace(".class", "").replace("/", "."));
        }
    }
    return res;
}

33. IO#unzip()

Project: SimpleServer
File: IO.java
public static void unzip(File zipfile, File directory) throws IOException {
    ZipFile zfile = new ZipFile(zipfile);
    Enumeration<? extends ZipEntry> entries = zfile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            file.getParentFile().mkdirs();
            InputStream in = zfile.getInputStream(entry);
            try {
                copy(in, file);
            } finally {
                in.close();
            }
        }
    }
}

34. ResourcesLoader#loadFile()

Project: show-java
File: ResourcesLoader.java
private void loadFile(List<ResourceFile> list, File file) {
    if (file == null) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            addEntry(list, file, entry);
        }
    } catch (IOException e) {
        LOG.debug("Not a zip file: {}", file.getAbsolutePath());
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (Exception e) {
                LOG.error("Zip file close error: {}", file.getAbsolutePath(), e);
            }
        }
    }
}

35. Utilities#getApkEntryBuildTime()

Project: reacteu-app
File: Utilities.java
public static long getApkEntryBuildTime(String entryName, Context context) {
    ZipFile applicationFile;
    long result = -1;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        applicationFile = new ZipFile(ai.sourceDir);
        ZipEntry classesDexEntry = applicationFile.getEntry(entryName);
        result = classesDexEntry.getTime();
        applicationFile.close();
    } catch (Exception e) {
    }
    return result;
}

36. ArchiveClassPathRoot#classNames()

Project: pitest
File: ArchiveClassPathRoot.java
@Override
public Collection<String> classNames() {
    final List<String> names = new ArrayList<String>();
    final ZipFile root = getRoot();
    try {
        final Enumeration<? extends ZipEntry> entries = root.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
                names.add(stringToClassName(entry.getName()));
            }
        }
        return names;
    } finally {
        closeQuietly(root);
    }
}

37. ArchiveClassPathRoot#getResource()

Project: pitest
File: ArchiveClassPathRoot.java
@Override
public URL getResource(final String name) throws MalformedURLException {
    final ZipFile zip = getRoot();
    try {
        final ZipEntry entry = zip.getEntry(name);
        if (entry != null) {
            return new URL("jar:file:" + zip.getName() + "!/" + entry.getName());
        } else {
            return null;
        }
    } finally {
        closeQuietly(zip);
    }
}

38. ArchiveClassPathRoot#getData()

Project: pitest
File: ArchiveClassPathRoot.java
@Override
public InputStream getData(final String name) throws IOException {
    final ZipFile zip = getRoot();
    try {
        final ZipEntry entry = zip.getEntry(name.replace('.', '/') + ".class");
        if (entry == null) {
            return null;
        }
        return StreamUtil.copyStream(zip.getInputStream(entry));
    } finally {
        // closes input stream
        zip.close();
    }
}

39. Utils#updateMap()

Project: pig
File: Utils.java
/**
     * Add entries to <code>packagedClasses</code> corresponding to class files
     * contained in <code>jar</code>.
     * 
     * @param jar
     *            The jar who's content to list.
     * @param packagedClasses
     *            map[class -> jar]
     */
private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
    if (null == jar || jar.isEmpty()) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements(); ) {
            ZipEntry entry = iter.nextElement();
            if (entry.getName().endsWith("class")) {
                packagedClasses.put(entry.getName(), jar);
            }
        }
    } finally {
        if (null != zip)
            zip.close();
    }
}

40. BackupTest#main()

Project: orientdb
File: BackupTest.java
public static void main(String[] args) throws IOException {
    File backupFile = new File("testbackup.zip");
    OutputStream oS = new FileOutputStream(backupFile);
    OrientGraphFactory factory = new OrientGraphFactory("plocal:backupTest", "admin", "admin");
    OrientGraphNoTx graphNoTx = factory.getNoTx();
    graphNoTx.getRawGraph().backup(oS, null, null, null, 1, 1024);
    ZipFile zipFile = new ZipFile(backupFile);
    Enumeration enumeration = zipFile.entries();
    System.out.format("ZipFile : %s%n", zipFile);
    while (enumeration.hasMoreElements()) {
        Object entry = enumeration.nextElement();
        System.out.format("  Entry : %s%n", entry);
    }
    factory.close();
}

41. CreateMultiReleaseTestJars#buildSignedMultiReleaseJar()

Project: openjdk
File: CreateMultiReleaseTestJars.java
public void buildSignedMultiReleaseJar() throws Exception {
    String testsrc = System.getProperty("test.src", ".");
    String testdir = findTestDir(testsrc);
    String keystore = testdir + "/sun/security/tools/jarsigner/JarSigning.keystore";
    // jarsigner -keystore keystore -storepass "bbbbbb"
    //           -signedJar signed-multi-release.jar multi-release.jar b
    char[] password = "bbbbbb".toCharArray();
    KeyStore ks = KeyStore.getInstance(new File(keystore), password);
    PrivateKey pkb = (PrivateKey) ks.getKey("b", password);
    CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(Arrays.asList(ks.getCertificateChain("b")));
    JarSigner js = new JarSigner.Builder(pkb, cp).build();
    try (ZipFile in = new ZipFile("multi-release.jar");
        FileOutputStream os = new FileOutputStream("signed-multi-release.jar")) {
        js.sign(in, os);
    }
}

42. ZipFSTester#test0()

Project: openjdk
File: ZipFSTester.java
static void test0(FileSystem fs) throws Exception {
    List<String> list = new LinkedList<>();
    try (ZipFile zf = new ZipFile(fs.toString())) {
        Enumeration<? extends ZipEntry> zes = zf.entries();
        while (zes.hasMoreElements()) {
            list.add(zes.nextElement().getName());
        }
        for (String pname : list) {
            Path path = fs.getPath(pname);
            if (!Files.exists(path))
                throw new RuntimeException("path existence check failed!");
            while ((path = path.getParent()) != null) {
                if (!Files.exists(path))
                    throw new RuntimeException("parent existence check failed!");
            }
        }
    }
}

43. MultiThreadedReadTest#main()

Project: openjdk
File: MultiThreadedReadTest.java
public static void main(String args[]) throws Exception {
    createZipFile();
    try (ZipFile zf = new ZipFile(new File(ZIPFILE_NAME))) {
        is = zf.getInputStream(zf.getEntry(ZIPENTRY_NAME));
        Thread[] threadArray = new Thread[NUM_THREADS];
        for (int i = 0; i < threadArray.length; i++) {
            threadArray[i] = new MultiThreadedReadTest();
        }
        for (int i = 0; i < threadArray.length; i++) {
            threadArray[i].start();
        }
        for (int i = 0; i < threadArray.length; i++) {
            threadArray[i].join();
        }
    } finally {
        FileUtils.deleteFileIfExistsWithRetry(Paths.get(ZIPFILE_NAME));
    }
}

44. FinalizeInflater#main()

Project: openjdk
File: FinalizeInflater.java
public static void main(String[] args) throws Throwable {
    try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip"))) {
        ZipEntry ze = zf.getEntry("ReadZip.java");
        read(zf.getInputStream(ze));
        System.gc();
        System.runFinalization();
        System.gc();
        // read again
        read(zf.getInputStream(ze));
    }
}

45. ClearStaleZipFileInputStreams#runTest()

Project: openjdk
File: ClearStaleZipFileInputStreams.java
private static void runTest(int compression) throws Exception {
    ReferenceQueue<InputStream> rq = new ReferenceQueue<>();
    System.out.println("Testing with a zip file with compression level = " + compression);
    File f = createTestFile(compression);
    try (ZipFile zf = new ZipFile(f)) {
        Set<Object> refSet = createTransientInputStreams(zf, rq);
        System.out.println("Waiting for 'stale' input streams from ZipFile to be GC'd ...");
        System.out.println("(The test will hang on failure)");
        while (false == refSet.isEmpty()) {
            refSet.remove(rq.remove());
        }
        System.out.println("Test PASSED.");
        System.out.println();
    } finally {
        f.delete();
    }
}

46. TestExtraTime#testTagOnlyHandling()

Project: openjdk
File: TestExtraTime.java
static void testTagOnlyHandling() throws Throwable {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] extra = new byte[] { 0x0a, 0, 4, 0, 0, 0, 0, 0 };
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        ZipEntry ze = new ZipEntry("TestExtraTime.java");
        ze.setExtra(extra);
        zos.putNextEntry(ze);
        zos.write(new byte[] { 1, 2, 3, 4 });
    }
    try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
        ZipEntry ze = zis.getNextEntry();
        check(ze, extra);
    }
    Path zpath = Paths.get(System.getProperty("test.dir", "."), "TestExtraTime.zip");
    Files.copy(new ByteArrayInputStream(baos.toByteArray()), zpath);
    try (ZipFile zf = new ZipFile(zpath.toFile())) {
        ZipEntry ze = zf.getEntry("TestExtraTime.java");
        check(ze, extra);
    } finally {
        Files.delete(zpath);
    }
}

47. JmodTask#describe()

Project: openjdk
File: JmodTask.java
private boolean describe() throws IOException {
    ZipFile zip = null;
    try {
        try {
            zip = new ZipFile(options.jmodFile.toFile());
        } catch (IOException x) {
            throw new IOException("error opening jmod file", x);
        }
        try (InputStream in = Files.newInputStream(options.jmodFile)) {
            boolean found = printModuleDescriptor(in);
            if (!found)
                throw new CommandException("err.module.descriptor.not.found");
            return found;
        }
    } finally {
        if (zip != null)
            zip.close();
    }
}

48. JmodTask#list()

Project: openjdk
File: JmodTask.java
private boolean list() throws IOException {
    ZipFile zip = null;
    try {
        try {
            zip = new ZipFile(options.jmodFile.toFile());
        } catch (IOException x) {
            throw new IOException("error opening jmod file", x);
        }
        // Trivially print the archive entries for now, pending a more complete implementation
        zip.stream().forEach( e -> out.println(e.getName()));
        return true;
    } finally {
        if (zip != null)
            zip.close();
    }
}

49. ModulePath#readJMod()

Project: openjdk
File: ModulePath.java
/**
     * Returns a {@code ModuleReference} to a module in jmod file on the
     * file system.
     *
     * @throws IOException
     * @throws InvalidModuleDescriptorException
     */
private ModuleReference readJMod(Path file) throws IOException {
    try (ZipFile zf = new ZipFile(file.toString())) {
        ZipEntry ze = zf.getEntry("classes/" + MODULE_INFO);
        if (ze == null) {
            throw new IOException(MODULE_INFO + " is missing: " + file);
        }
        ModuleDescriptor md;
        try (InputStream in = zf.getInputStream(ze)) {
            md = ModuleDescriptor.read(in, () -> jmodPackages(zf));
        }
        return ModuleReferences.newJModModule(md, file);
    }
}

50. __JDKPaths#processJar()

Project: Nicobar
File: __JDKPaths.java
static void processJar(final Set<String> pathSet, final File file) throws IOException {
    final ZipFile zipFile = new ZipFile(file);
    try {
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            final int lastSlash = name.lastIndexOf('/');
            if (lastSlash != -1) {
                pathSet.add(name.substring(0, lastSlash));
            }
        }
        zipFile.close();
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
}

51. ClassPathUtils#getDirectoriesFromJar()

Project: Nicobar
File: ClassPathUtils.java
/**
     * Get all of the directory paths in a zip/jar file
     * @param pathToJarFile location of the jarfile. can also be a zipfile
     * @return set of directory paths relative to the root of the jar
     */
public static Set<Path> getDirectoriesFromJar(Path pathToJarFile) throws IOException {
    Set<Path> result = new HashSet<Path>();
    ZipFile jarfile = new ZipFile(pathToJarFile.toFile());
    try {
        final Enumeration<? extends ZipEntry> entries = jarfile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                result.add(Paths.get(entry.getName()));
            }
        }
        jarfile.close();
    } finally {
        IOUtils.closeQuietly(jarfile);
    }
    return result;
}

52. CMRTests#testMavenFileResolver()

Project: ceylon
File: CMRTests.java
@Test
public void testMavenFileResolver() throws ZipException, IOException {
    CeylonRepoManagerBuilder builder = CeylonUtils.repoManager();
    RepositoryManager repository = builder.buildManager();
    String groupId = "javax.el";
    String artifactId = "javax.el-api";
    String version = "3.0.0";
    String coord = groupId + ":" + artifactId;
    File artifact = repository.getArtifact(MavenArtifactContext.NAMESPACE, coord, version);
    Assert.assertNotNull(artifact);
    try (ZipFile zf = new ZipFile(artifact)) {
        String descriptorPath = String.format("META-INF/maven/%s/%s/pom.xml", groupId, artifactId);
        ZipEntry entry = zf.getEntry(descriptorPath);
        Assert.assertNotNull(entry);
        try (InputStream is = zf.getInputStream(entry)) {
            DependencyResolver resolver = new MavenDependencyResolver();
            ModuleInfo info = resolver.resolveFromInputStream(is, coord, version, null);
            Assert.assertNotNull(info);
            // FIXME: find one with dependencies
            System.err.println(info.getDependencies());
        }
    }
}

53. SparkRuntimeUtilsTest#testCreateConfArchive()

Project: cdap
File: SparkRuntimeUtilsTest.java
@Test
public void testCreateConfArchive() throws IOException {
    File confDir = TEMP_FOLDER.newFolder();
    File confFile = new File(confDir, "testing.conf");
    Files.write("Testing Message", confFile, Charsets.UTF_8);
    SparkConf conf = new SparkConf();
    conf.set("testing", "value");
    File archiveFile = SparkRuntimeUtils.createConfArchive(conf, "test.properties", confDir.getAbsolutePath(), TEMP_FOLDER.newFile().getAbsolutePath());
    try (ZipFile zipFile = new ZipFile(archiveFile)) {
        Properties properties = new Properties();
        try (InputStream is = zipFile.getInputStream(zipFile.getEntry("test.properties"))) {
            properties.load(is);
            Assert.assertEquals("value", properties.getProperty("testing"));
        }
        try (InputStream is = zipFile.getInputStream(zipFile.getEntry("testing.conf"))) {
            Assert.assertEquals("Testing Message", Bytes.toString(ByteStreams.toByteArray(is)));
        }
    }
}

54. AbiClass#extract()

Project: buck
File: AbiClass.java
public static AbiClass extract(Path pathToJar, String className) throws IOException {
    try (ZipFile zip = new ZipFile(pathToJar.toString())) {
        ZipEntry entry = zip.getEntry(className);
        try (InputStream entryStream = zip.getInputStream(entry)) {
            ClassReader reader = new ClassReader(entryStream);
            ClassNode classNode = new ClassNode();
            reader.accept(classNode, 0);
            return new AbiClass(classNode);
        }
    }
}

55. ProGuardObfuscateStepTest#testCreateEmptyZip()

Project: buck
File: ProGuardObfuscateStepTest.java
@Test
public void testCreateEmptyZip() throws Exception {
    Path tmpFile = tmpDir.newFile();
    ProGuardObfuscateStep.createEmptyZip(tmpFile);
    // Try to read it.
    try (ZipFile zipFile = new ZipFile(tmpFile.toFile())) {
        int totalSize = 0;
        List<? extends ZipEntry> entries = Collections.list(zipFile.entries());
        assertTrue("Expected either 0 or 1 entry", entries.size() <= 1);
        for (ZipEntry entry : entries) {
            totalSize += entry.getSize();
        }
        assertEquals("Zip file should have zero-length contents", 0, totalSize);
    }
}

56. DxAnalysisMain#loadAllClasses()

Project: buck
File: DxAnalysisMain.java
private static ImmutableMap<String, ClassNode> loadAllClasses(String zipFileName) throws IOException {
    ImmutableMap.Builder<String, ClassNode> allClassesBuilder = ImmutableMap.builder();
    try (ZipFile inJar = new ZipFile(zipFileName)) {
        for (ZipEntry entry : Collections.list(inJar.entries())) {
            if (!entry.getName().endsWith(".class")) {
                continue;
            }
            // Skip external libraries.
            if (entry.getName().startsWith("junit/") || entry.getName().startsWith("org/junit/") || entry.getName().startsWith("com/google/common/")) {
                continue;
            }
            byte[] rawClass = ByteStreams.toByteArray(inJar.getInputStream(entry));
            ClassNode klass = new ClassNode();
            new ClassReader(rawClass).accept(klass, ClassReader.EXPAND_FRAMES);
            allClassesBuilder.put(klass.name, klass);
        }
    }
    return allClassesBuilder.build();
}

57. ProjectFilesystem#getZipMembers()

Project: buck
File: ProjectFilesystem.java
public ImmutableCollection<Path> getZipMembers(Path archivePath) throws IOException {
    Path archiveAbsolutePath = archivePath.isAbsolute() ? archivePath : getPathForRelativePath(archivePath);
    try (ZipFile zip = new ZipFile(archiveAbsolutePath.toFile())) {
        return ImmutableList.copyOf(Iterators.transform(Iterators.forEnumeration(zip.entries()), new Function<ZipEntry, Path>() {

            @Override
            public Path apply(ZipEntry input) {
                return Paths.get(input.getName());
            }
        }));
    }
}

58. SplitZipStep#findAnyClass()

Project: buck
File: SplitZipStep.java
private static String findAnyClass(Path jarFile) throws IOException {
    try (ZipFile inZip = new ZipFile(jarFile.toFile())) {
        for (ZipEntry entry : Collections.list(inZip.entries())) {
            Matcher m = CLASS_FILE_PATTERN.matcher(entry.getName());
            if (m.matches()) {
                return m.group(1).replace('/', '.');
            }
        }
    }
    // TODO(dreiss): It's possible for this to happen by chance, so we should handle it better.
    throw new IllegalStateException("Couldn't find any class in " + jarFile.toAbsolutePath());
}

59. IjarTests#testVerifyStripping()

Project: bazel
File: IjarTests.java
@Test
public void testVerifyStripping() throws Exception {
    ZipFile zip = new ZipFile("third_party/ijar/test/interface_ijar_testlib.jar");
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        ClassReader reader = new ClassReader(zip.getInputStream(entry));
        StripVerifyingVisitor verifier = new StripVerifyingVisitor();
        reader.accept(verifier, 0);
        if (verifier.errors.size() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append("Verification of ");
            builder.append(entry.getName());
            builder.append(" failed: ");
            for (String msg : verifier.errors) {
                builder.append(msg);
                builder.append("\t");
            }
            fail(builder.toString());
        }
    }
}

60. Classpath#findClassesInJar()

Project: bazel
File: Classpath.java
/**
   * Returns a set of all classes in the jar that start with the given prefix.
   */
private static Set<String> findClassesInJar(File jarFile, String pathPrefix) throws IOException {
    Set<String> classNames = new TreeSet<>();
    try (ZipFile zipFile = new ZipFile(jarFile)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement().getName();
            if (entryName.startsWith(pathPrefix) && entryName.endsWith(CLASS_EXTENSION)) {
                classNames.add(getClassName(entryName));
            }
        }
    }
    return classNames;
}

61. IdlClassTest#getJarEntries()

Project: bazel
File: IdlClassTest.java
private List<String> getJarEntries(File outputJar) throws IOException {
    List<String> jarEntries = new ArrayList<>();
    try (ZipFile zf = new ZipFile(outputJar)) {
        Enumeration<? extends ZipEntry> entries = zf.entries();
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.endsWith("/") || name.equals("META-INF/MANIFEST.MF")) {
                continue;
            }
            jarEntries.add(name);
        }
    }
    return jarEntries;
}

62. AndroidResourceCompilationActionTest#noBinary()

Project: bazel
File: AndroidResourceCompilationActionTest.java
@Test
public void noBinary() throws Exception {
    Path jarPath = tempDir.resolve("app_resources.jar");
    AndroidResourceCompilationAction.main(ImmutableList.<String>of("--classJarOutput", jarPath.toString()).toArray(new String[0]));
    assertThat(Files.exists(jarPath)).isTrue();
    assertThat(Files.getLastModifiedTime(jarPath)).isEqualTo(FileTime.fromMillis(0));
    try (ZipFile zip = new ZipFile(jarPath.toFile())) {
        List<? extends ZipEntry> zipEntries = Collections.list(zip.entries());
        Iterable<String> entries = getZipFilenames(zipEntries);
        assertThat(entries).containsExactly(Paths.get("META-INF/MANIFEST.MF").toString());
    }
}

63. ZipWriterTest#testZip64_FileSize_Zip64Range()

Project: bazel
File: ZipWriterTest.java
@Test
public void testZip64_FileSize_Zip64Range() throws IOException {
    long size = 0x1000000ffL;
    try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8, true)) {
        ZipFileEntry entry = new ZipFileEntry("big");
        entry.setCompressedSize(size);
        entry.setSize(size);
        entry.setCrc(0);
        entry.setTime(cal.getTimeInMillis());
        writer.putNextEntry(entry);
        byte[] chunk = new byte[1024];
        for (int i = 0; i < size / chunk.length; i++) {
            writer.write(chunk);
        }
        writer.write(chunk, 0, (int) (size % chunk.length));
        writer.closeEntry();
    }
    try (ZipFile file = new ZipFile(test)) {
        ZipEntry entry = file.getEntry("big");
        assertThat(entry.getSize()).isEqualTo(size);
        assertThat(entry.getCompressedSize()).isEqualTo(size);
    }
}

64. ZipWriterTest#testZip64_FileSize_32BitMax()

Project: bazel
File: ZipWriterTest.java
@Test
public void testZip64_FileSize_32BitMax() throws IOException {
    long size = 0xffffffffL;
    try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8, true)) {
        ZipFileEntry entry = new ZipFileEntry("big");
        entry.setCompressedSize(size);
        entry.setSize(size);
        entry.setCrc(0);
        entry.setTime(cal.getTimeInMillis());
        writer.putNextEntry(entry);
        byte[] chunk = new byte[1024];
        for (int i = 0; i < size / chunk.length; i++) {
            writer.write(chunk);
        }
        writer.write(chunk, 0, (int) (size % chunk.length));
        writer.closeEntry();
    }
    try (ZipFile file = new ZipFile(test)) {
        ZipEntry entry = file.getEntry("big");
        assertThat(entry.getSize()).isEqualTo(size);
        assertThat(entry.getCompressedSize()).isEqualTo(size);
    }
}

65. ZipWriterTest#testFileDataBeforeEntry()

Project: bazel
File: ZipWriterTest.java
@Test
public void testFileDataBeforeEntry() throws IOException {
    try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
        writer.write(new byte[] { 0xf, 0xa, 0xb });
        fail("Expected ZipException");
    } catch (ZipException e) {
        assertThat(e.getMessage()).contains("Cannot write zip contents without first setting a" + " ZipEntry or starting a prefix file.");
    }
    try (ZipFile zipFile = new ZipFile(test)) {
        assertThat(zipFile.entries().hasMoreElements()).isFalse();
    }
}

66. WindGateIoProcessorRunTest#loadScript()

Project: asakusafw
File: WindGateIoProcessorRunTest.java
private GateScript loadScript(JobflowInfo info, String profile, boolean importer) throws IOException {
    File file = info.getPackageFile();
    try (ZipFile zip = new ZipFile(file)) {
        String location = WindGateIoProcessor.getScriptLocation(importer, profile);
        ZipEntry entry = zip.getEntry(location);
        assertThat(entry, is(notNullValue()));
        Properties p = new Properties();
        try (InputStream input = zip.getInputStream(entry)) {
            p.load(input);
        }
        return GateScript.loadFrom("dummy", p, getClass().getClassLoader());
    }
}

67. LauncherOptionsParser#isInclude()

Project: asakusafw
File: LauncherOptionsParser.java
private boolean isInclude(File file, String className) {
    try (ZipFile zip = new ZipFile(file)) {
        //$NON-NLS-1$
        return zip.getEntry(className.replace('.', '/') + ".class") != null;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Exception occurred while detecting for class: file={0}, class={1}", file, className), e);
        }
    }
    return false;
}

68. TomcatUtil#isZip()

Project: armeria
File: TomcatUtil.java
static boolean isZip(Path path) {
    if (!Files.isRegularFile(path)) {
        return false;
    }
    try (ZipFile ignored = new ZipFile(path.toFile())) {
        return true;
    } catch (IOException ignored) {
        return false;
    }
}

69. ZipFileImpl#openZipFile()

Project: aries
File: ZipFileImpl.java
ZipFile openZipFile() {
    ZipFile z = null;
    if (cache != null && !!!cache.isClosed()) {
        z = cache.getZipFile();
    } else {
        try {
            z = new ZipFile(zip);
        } catch (IOException e) {
            throw new IORuntimeException("IOException in ZipFileImpl.openZipFile", e);
        }
    }
    return z;
}

70. ZipDirectory#listFiles()

Project: aries
File: ZipDirectory.java
private List<IFile> listFiles(boolean includeFilesInNestedSubdirs) {
    List<IFile> files = new ArrayList<IFile>();
    ZipFile z = openZipFile();
    List<? extends ZipEntry> entries = Collections.list(z.entries());
    for (ZipEntry possibleEntry : entries) {
        if (isInDir(getNameInZip(), possibleEntry, includeFilesInNestedSubdirs)) {
            ZipDirectory parent = includeFilesInNestedSubdirs ? buildParent(possibleEntry) : this;
            if (possibleEntry.isDirectory()) {
                files.add(new ZipDirectory(zip, possibleEntry, parent, cache));
            } else {
                files.add(new ZipFileImpl(zip, possibleEntry, parent, cache));
            }
        }
    }
    closeZipFile(z);
    return files;
}

71. PluginClassLoader#findClassContent()

Project: apiman
File: PluginClassLoader.java
/**
     * Searches the plugin artifact ZIP and all dependency ZIPs for a zip entry for
     * the given fully qualified class name.
     * @param className name of class
     * @throws IOException if an I/O error has occurred
     */
protected InputStream findClassContent(String className) throws IOException {
    String primaryArtifactEntryName = "WEB-INF/classes/" + className.replace('.', '/') + ".class";
    String dependencyEntryName = className.replace('.', '/') + ".class";
    ZipEntry entry = this.pluginArtifactZip.getEntry(primaryArtifactEntryName);
    if (entry != null) {
        return this.pluginArtifactZip.getInputStream(entry);
    }
    for (ZipFile zipFile : this.dependencyZips) {
        entry = zipFile.getEntry(dependencyEntryName);
        if (entry != null) {
            return zipFile.getInputStream(entry);
        }
    }
    return null;
}

72. ZipFileImpl#openZipFile()

Project: apache-aries
File: ZipFileImpl.java
ZipFile openZipFile() {
    ZipFile z = null;
    if (cache != null && !!!cache.isClosed()) {
        z = cache.getZipFile();
    } else {
        try {
            z = new ZipFile(zip);
        } catch (IOException e) {
            throw new IORuntimeException("IOException in ZipFileImpl.openZipFile", e);
        }
    }
    return z;
}

73. ZipDirectory#listFiles()

Project: apache-aries
File: ZipDirectory.java
private List<IFile> listFiles(boolean includeFilesInNestedSubdirs) {
    List<IFile> files = new ArrayList<IFile>();
    ZipFile z = openZipFile();
    List<? extends ZipEntry> entries = Collections.list(z.entries());
    for (ZipEntry possibleEntry : entries) {
        if (isInDir(getNameInZip(), possibleEntry, includeFilesInNestedSubdirs)) {
            ZipDirectory parent = includeFilesInNestedSubdirs ? buildParent(possibleEntry) : this;
            if (possibleEntry.isDirectory()) {
                files.add(new ZipDirectory(zip, possibleEntry, parent, cache));
            } else {
                files.add(new ZipFileImpl(zip, possibleEntry, parent, cache));
            }
        }
    }
    closeZipFile(z);
    return files;
}

74. ManifestReader#getManifestXMLFromAPK()

Project: Android-Plugin-Framework
File: ManifestReader.java
public static String getManifestXMLFromAPK(String apkPath) {
    ZipFile file = null;
    String rs = null;
    try {
        File apkFile = new File(apkPath);
        file = new ZipFile(apkFile, ZipFile.OPEN_READ);
        ZipEntry entry = file.getEntry(DEFAULT_XML);
        rs = getManifestXMLFromAPK(file, entry);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return rs;
}

75. ApkMojo#computeDuplicateFiles()

Project: android-maven-plugin
File: ApkMojo.java
private void computeDuplicateFiles(File jar) throws IOException {
    ZipFile file = new ZipFile(jar);
    Enumeration<? extends ZipEntry> list = file.entries();
    while (list.hasMoreElements()) {
        ZipEntry ze = list.nextElement();
        if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) {
            // Exclude META-INF and Directories
            List<File> l = jars.get(ze.getName());
            if (l == null) {
                l = new ArrayList<File>();
                jars.put(ze.getName(), l);
            }
            l.add(jar);
        }
    }
}

76. XmlManifestReader#getManifestXMLFromAPK()

Project: android-dynamical-loading
File: XmlManifestReader.java
public static String getManifestXMLFromAPK(String apkPath) {
    ZipFile file = null;
    String rs = null;
    try {
        File apkFile = new File(apkPath);
        file = new ZipFile(apkFile, ZipFile.OPEN_READ);
        ZipEntry entry = file.getEntry(DEFAULT_XML);
        rs = getManifestXMLFromAPK(file, entry);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return rs;
}

77. ApkUtils#getFiles()

Project: android-arscblamer
File: ApkUtils.java
/**
   * Returns all files in an apk that match a given regular expression.
   *
   * @param apkFile The file containing the apk zip archive.
   * @param regex A regular expression to match the requested filenames.
   * @return A mapping of the matched filenames to their byte contents.
   * @throws IOException Thrown if a matching file cannot be read from the apk.
   */
public static Map<String, byte[]> getFiles(File apkFile, Pattern regex) throws IOException {
    // Retain insertion order
    Map<String, byte[]> files = new LinkedHashMap<>();
    // Extract apk
    try (ZipFile apkZip = new ZipFile(apkFile)) {
        Enumeration<? extends ZipEntry> zipEntries = apkZip.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            // Visit all files with the given extension
            if (regex.matcher(zipEntry.getName()).matches()) {
                // Map class name to definition
                try (InputStream is = new BufferedInputStream(apkZip.getInputStream(zipEntry))) {
                    files.put(zipEntry.getName(), ByteStreams.toByteArray(is));
                }
            }
        }
    }
    return files;
}

78. JavadocsEntryAttacher#getJavaDocPathInArchive()

Project: m2e-android
File: JavadocsEntryAttacher.java
private static String getJavaDocPathInArchive(File file) throws ZipException, IOException {
    ZipFile jarFile = null;
    try {
        jarFile = new ZipFile(file);
        String marker = "package-list";
        for (Enumeration<? extends ZipEntry> en = jarFile.entries(); en.hasMoreElements(); ) {
            ZipEntry entry = en.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(marker)) {
                return entry.getName().substring(0, entryName.length() - marker.length());
            }
        }
    } finally {
        if (jarFile != null)
            jarFile.close();
    }
    throw new ProjectConfigurationException("error finding javadoc path in JAR=[" + file + "]");
}

79. FileResourcePack#getInputStreamByName()

Project: Kingdoms
File: FileResourcePack.java
protected InputStream getInputStreamByName(String name) throws IOException {
    ZipFile zipfile = this.getResourcePackZipFile();
    ZipEntry zipentry = zipfile.getEntry(name);
    if (zipentry == null) {
        throw new ResourcePackFileNotFoundException(this.resourcePackFile, name);
    } else {
        return zipfile.getInputStream(zipentry);
    }
}

80. FinalizeInflater#main()

Project: jdk7u-jdk
File: FinalizeInflater.java
public static void main(String[] args) throws Throwable {
    try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip"))) {
        ZipEntry ze = zf.getEntry("ReadZip.java");
        read(zf.getInputStream(ze));
        System.gc();
        System.runFinalization();
        System.gc();
        // read again
        read(zf.getInputStream(ze));
    }
}

81. JDKPaths#processJar()

Project: jboss-modules
File: JDKPaths.java
static void processJar(final Set<String> pathSet, final File file) throws IOException {
    final ZipFile zipFile = new ZipFile(file);
    try {
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            final int lastSlash = name.lastIndexOf('/');
            if (lastSlash != -1) {
                pathSet.add(name.substring(0, lastSlash));
            }
        }
        zipFile.close();
    } finally {
        StreamUtil.safeClose(zipFile);
    }
}

82. ResourcesLoader#loadFile()

Project: jadx
File: ResourcesLoader.java
private void loadFile(List<ResourceFile> list, File file) {
    if (file == null) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            addEntry(list, file, entry);
        }
    } catch (IOException e) {
        LOG.debug("Not a zip file: {}", file.getAbsolutePath());
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (Exception e) {
                LOG.error("Zip file close error: {}", file.getAbsolutePath(), e);
            }
        }
    }
}

83. Zip64FileTest#testZip64Support_largeNumberOfEntries()

Project: j2objc
File: Zip64FileTest.java
public void testZip64Support_largeNumberOfEntries() throws IOException {
    final File file = createZipFile(65550, 2, false);
    ZipFile zf = null;
    try {
        zf = new ZipFile(file);
        assertEquals(65550, zf.size());
        Enumeration<? extends ZipEntry> entries = zf.entries();
        assertTrue(entries.hasMoreElements());
        ZipEntry ze = entries.nextElement();
        assertEquals(2, ze.getSize());
    } finally {
        if (zf != null) {
            zf.close();
        }
    }
}

84. AbstractZipFileTest#testZipFileErrorReadingData()

Project: j2objc
File: AbstractZipFileTest.java
public void testZipFileErrorReadingData() throws IOException {
    File resources = Support_Resources.createTempFolder();
    File tempZipFile = Support_Resources.copyFile(resources, "java/util/zip", "ZipFileBreak.zip");
    String tempZipFilePath = tempZipFile.getAbsolutePath();
    try (ZipFile zipFile = new ZipFile(tempZipFilePath)) {
        ZipEntry entry = zipFile.getEntry("subdir/file.txt");
        assertNotNull(entry);
        byte[] content = toByteArray(zipFile.getInputStream(entry));
        assertNotNull(content);
        entry = zipFile.getEntry("subdir/file.pb");
        assertNotNull(entry);
        content = toByteArray(zipFile.getInputStream(entry));
        assertNotNull(content);
    }
}

85. ZipUtils#unzip()

Project: ios-driver
File: ZipUtils.java
//
public static void unzip(File zipFile, File targetDir) throws IOException {
    String targetDirPath = targetDir.getAbsolutePath() + '/';
    if (!targetDir.exists())
        targetDir.mkdirs();
    ZipFile zip = new ZipFile(zipFile);
    try {
        for (ZipEntry entry : Collections.list(zip.entries())) {
            if (entry.isDirectory())
                continue;
            InputStream input = zip.getInputStream(entry);
            try {
                File target = new File(targetDirPath + entry.getName());
                FileUtils.copyInputStreamToFile(input, target);
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    } finally {
        zip.close();
    }
}

86. PatchFileCreator#revert()

Project: intellij-community
File: PatchFileCreator.java
public static void revert(PreparationResult preparationResult, List<PatchAction> actionsToRevert, File backupDir, UpdaterUI ui) throws IOException, OperationCancelledException {
    ZipFile zipFile = new ZipFile(preparationResult.patchFile);
    try {
        preparationResult.patch.revert(actionsToRevert, backupDir, preparationResult.toDir, ui);
    } finally {
        zipFile.close();
    }
}

87. PatchFileCreator#apply()

Project: intellij-community
File: PatchFileCreator.java
public static Patch.ApplicationResult apply(PreparationResult preparationResult, Map<String, ValidationResult.Option> options, File backupDir, UpdaterUI ui) throws IOException, OperationCancelledException {
    ZipFile zipFile = new ZipFile(preparationResult.patchFile);
    try {
        return preparationResult.patch.apply(zipFile, preparationResult.toDir, backupDir, options, ui);
    } finally {
        zipFile.close();
    }
}

88. PatchFileCreator#prepareAndValidate()

Project: intellij-community
File: PatchFileCreator.java
public static PreparationResult prepareAndValidate(File patchFile, File toDir, UpdaterUI ui) throws IOException, OperationCancelledException {
    Patch patch;
    ZipFile zipFile = new ZipFile(patchFile);
    try {
        InputStream in = Utils.getEntryInputStream(zipFile, PATCH_INFO_FILE_NAME);
        try {
            patch = new Patch(in);
        } finally {
            in.close();
        }
    } finally {
        zipFile.close();
    }
    ui.setDescription(patch.getOldBuild(), patch.getNewBuild());
    List<ValidationResult> validationResults = patch.validate(toDir, ui);
    return new PreparationResult(patch, patchFile, toDir, validationResults);
}

89. BulkDecompilationTest#unpack()

Project: intellij-community
File: BulkDecompilationTest.java
private static void unpack(File archive, File targetDir) {
    try (ZipFile zip = new ZipFile(archive)) {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                File file = new File(targetDir, entry.getName());
                assertTrue(file.getParentFile().mkdirs() || file.getParentFile().isDirectory());
                try (InputStream in = zip.getInputStream(entry);
                    OutputStream out = new FileOutputStream(file)) {
                    InterpreterUtil.copyStream(in, out);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

90. ConsoleDecompiler#copyEntry()

Project: intellij-community
File: ConsoleDecompiler.java
@Override
public void copyEntry(String source, String path, String archiveName, String entryName) {
    String file = new File(getAbsolutePath(path), archiveName).getPath();
    if (!checkEntry(entryName, file)) {
        return;
    }
    try (ZipFile srcArchive = new ZipFile(new File(source))) {
        ZipEntry entry = srcArchive.getEntry(entryName);
        if (entry != null) {
            try (InputStream in = srcArchive.getInputStream(entry)) {
                ZipOutputStream out = mapArchiveStreams.get(file);
                out.putNextEntry(new ZipEntry(entryName));
                InterpreterUtil.copyStream(in, out);
            }
        }
    } catch (IOException ex) {
        String message = "Cannot copy entry " + entryName + " from " + source + " to " + file;
        DecompilerContext.getLogger().writeMessage(message, ex);
    }
}

91. JarLoader#buildData()

Project: intellij-community
File: JarLoader.java
@NotNull
@Override
public ClasspathCache.LoaderData buildData() throws IOException {
    ZipFile zipFile = getZipFile();
    try {
        ClasspathCache.LoaderData loaderData = new ClasspathCache.LoaderData();
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();
            loaderData.addResourceEntry(name);
            loaderData.addNameEntry(name);
        }
        return loaderData;
    } finally {
        releaseZipFile(zipFile);
    }
}

92. ZipUtil#isZipContainsEntry()

Project: intellij-community
File: ZipUtil.java
public static boolean isZipContainsEntry(File zip, String relativePath) throws IOException {
    ZipFile zipFile = new ZipFile(zip);
    try {
        Enumeration en = zipFile.entries();
        while (en.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) en.nextElement();
            if (relativePath.equals(zipEntry.getName())) {
                return true;
            }
        }
        zipFile.close();
        return false;
    } finally {
        zipFile.close();
    }
}

93. ZipUtil#isZipContainsFolder()

Project: intellij-community
File: ZipUtil.java
public static boolean isZipContainsFolder(File zip) throws IOException {
    ZipFile zipFile = new ZipFile(zip);
    try {
        Enumeration en = zipFile.entries();
        while (en.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) en.nextElement();
            // is found anywhere in the path
            if (zipEntry.getName().indexOf('/') >= 0) {
                return true;
            }
        }
        zipFile.close();
        return false;
    } finally {
        zipFile.close();
    }
}

94. URLUtil#openJarStream()

Project: intellij-community
File: URLUtil.java
@NotNull
private static InputStream openJarStream(@NotNull URL url) throws IOException {
    Pair<String, String> paths = splitJarUrl(url.getFile());
    if (paths == null) {
        throw new MalformedURLException(url.getFile());
    }
    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(paths.first);
    ZipEntry zipEntry = zipFile.getEntry(paths.second);
    if (zipEntry == null) {
        zipFile.close();
        throw new FileNotFoundException("Entry " + paths.second + " not found in " + paths.first);
    }
    return new FilterInputStream(zipFile.getInputStream(zipEntry)) {

        @Override
        public void close() throws IOException {
            super.close();
            zipFile.close();
        }
    };
}

95. ZipUtil#unzip()

Project: intellij-community
File: ZipUtil.java
// This method will throw IOException, if a zipArchive file isn't a valid zip archive.
public static void unzip(@Nullable ProgressIndicator progress, @NotNull File targetDir, @NotNull File zipArchive, @Nullable NullableFunction<String, String> pathConvertor, @Nullable ContentProcessor contentProcessor, boolean unwrapSingleTopLevelFolder) throws IOException {
    File unzipToDir = getUnzipToDir(progress, targetDir, unwrapSingleTopLevelFolder);
    ZipFile zipFile = new ZipFile(zipArchive, ZipFile.OPEN_READ);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            InputStream entryContentStream = zipFile.getInputStream(entry);
            unzipEntryToDir(progress, entry, entryContentStream, unzipToDir, pathConvertor, contentProcessor);
            entryContentStream.close();
        }
    } finally {
        zipFile.close();
    }
    doUnwrapSingleTopLevelFolder(unwrapSingleTopLevelFolder, unzipToDir, targetDir);
}

96. JavaModuleInsight#scanLibraryForDeclaredPackages()

Project: intellij-community
File: JavaModuleInsight.java
@Override
protected void scanLibraryForDeclaredPackages(File file, Consumer<String> result) throws IOException {
    final ZipFile zip = new ZipFile(file);
    try {
        final Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            final String entryName = entries.nextElement().getName();
            if (StringUtil.endsWithIgnoreCase(entryName, ".class")) {
                final int index = entryName.lastIndexOf('/');
                if (index > 0) {
                    final String packageName = entryName.substring(0, index).replace('/', '.');
                    result.consume(packageName);
                }
            }
        }
    } finally {
        zip.close();
    }
}

97. ZipFilesTest#testAsCharSource()

Project: incubator-beam
File: ZipFilesTest.java
@Test
public void testAsCharSource() throws Exception {
    File zipDir = new File(tmpDir, "zip");
    assertTrue(zipDir.mkdirs());
    createFileWithContents(zipDir, "myTextFile.txt", "Simple Text");
    ZipFiles.zipDirectory(tmpDir, zipFile);
    try (ZipFile zip = new ZipFile(zipFile)) {
        ZipEntry entry = zip.getEntry("zip/myTextFile.txt");
        CharSource charSource = ZipFiles.asCharSource(zip, entry, StandardCharsets.UTF_8);
        assertEquals("Simple Text", charSource.read());
    }
}

98. ZipFilesTest#testAsByteSource()

Project: incubator-beam
File: ZipFilesTest.java
@Test
public void testAsByteSource() throws Exception {
    File zipDir = new File(tmpDir, "zip");
    assertTrue(zipDir.mkdirs());
    createFileWithContents(zipDir, "myTextFile.txt", "Simple Text");
    ZipFiles.zipDirectory(tmpDir, zipFile);
    try (ZipFile zip = new ZipFile(zipFile)) {
        ZipEntry entry = zip.getEntry("zip/myTextFile.txt");
        ByteSource byteSource = ZipFiles.asByteSource(zip, entry);
        if (entry.getSize() != -1) {
            assertEquals(entry.getSize(), byteSource.size());
        }
        assertArrayEquals("Simple Text".getBytes(StandardCharsets.UTF_8), byteSource.read());
    }
}

99. ZipFilesTest#testEntries()

Project: incubator-beam
File: ZipFilesTest.java
@Test
public void testEntries() throws Exception {
    File zipDir = new File(tmpDir, "zip");
    File subDir1 = new File(zipDir, "subDir1");
    File subDir2 = new File(subDir1, "subdir2");
    assertTrue(subDir2.mkdirs());
    createFileWithContents(subDir2, "myTextFile.txt", "Simple Text");
    ZipFiles.zipDirectory(tmpDir, zipFile);
    ZipFile zip = new ZipFile(zipFile);
    try {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        for (ZipEntry entry : ZipFiles.entries(zip)) {
            assertTrue(entries.hasMoreElements());
            // ZipEntry doesn't override equals
            assertEquals(entry.getName(), entries.nextElement().getName());
        }
        assertFalse(entries.hasMoreElements());
    } finally {
        zip.close();
    }
}

100. ZipUtil#unzip()

Project: hutool
File: ZipUtil.java
/**
	 * ??
	 * 
	 * @param zipFile zip??
	 * @param outFile ??????
	 * @return ?????
	 * @throws IOException
	 */
@SuppressWarnings("unchecked")
public static File unzip(File zipFile, File outFile) throws IOException {
    final ZipFile zipFileObj = new ZipFile(zipFile);
    final Enumeration<ZipEntry> em = (Enumeration<ZipEntry>) zipFileObj.entries();
    ZipEntry zipEntry = null;
    File outItemFile = null;
    while (em.hasMoreElements()) {
        zipEntry = em.nextElement();
        outItemFile = new File(outFile, zipEntry.getName());
        log.debug("UNZIP {}", outItemFile.getPath());
        if (zipEntry.isDirectory()) {
            outItemFile.mkdirs();
        } else {
            FileUtil.touch(outItemFile);
            copy(zipFileObj, zipEntry, outItemFile);
        }
    }
    IoUtil.close(zipFileObj);
    return outFile;
}