Java Code Examples for java.util.zip.ZipFile#close()

The following examples show how to use java.util.zip.ZipFile#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Dex.java    From Box with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new dex buffer from the dex file {@code file}.
 */
public Dex(File file) throws IOException {
    if (FileUtils.hasArchiveSuffix(file.getName())) {
        ZipFile zipFile = new ZipFile(file);
        ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME);
        if (entry != null) {
            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                loadFrom(inputStream);
            }
            zipFile.close();
        } else {
            throw new DexException("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file);
        }
    } else if (file.getName().endsWith(".dex")) {
        try (InputStream inputStream = new FileInputStream(file)) {
            loadFrom(inputStream);
        }
    } else {
        throw new DexException("unknown output extension: " + file);
    }
}
 
Example 2
Source File: EnvironmentUtils.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
private static ZipFile getZipFile(URL url) {
	try {
		URI uri = url.toURI();

		File file = new File(uri);

		ZipFile zipFile = new ZipFile(file);
		if (zipFile.getEntry("eu/the5zig/mod/The5zigMod.class") == null) {
			zipFile.close();
			return null;
		}
		return zipFile;
	} catch (Exception ignored) {
		return null;
	}
}
 
Example 3
Source File: ClassFileLocatorForModuleFileTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonSuccessfulLocation() throws Exception {
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
    try {
        ZipEntry zipEntry = new ZipEntry("noop.class");
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.write(VALUE);
        zipOutputStream.closeEntry();
    } finally {
        zipOutputStream.close();
    }
    ZipFile zipFile = new ZipFile(file);
    try {
        ClassFileLocator classFileLocator = new ClassFileLocator.ForModuleFile(zipFile);
        ClassFileLocator.Resolution resolution = classFileLocator.locate(FOO + "." + BAR);
        assertThat(resolution.isResolved(), is(false));
    } finally {
        zipFile.close();
    }
}
 
Example 4
Source File: AbstractZipFileTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testReadMoreThan8kInOneRead() throws IOException {
    // Create a zip file with 1mb entry
    final File f = createTemporaryZipFile();
    writeEntries(createZipOutputStream(f), 1, 1024 * 1024, true /* setEntrySize */);

    // Create a ~64kb read buffer (-32 bytes for a slack, inflater wont fill it completly)
    byte[] readBuffer = new byte[1024 * 64 - 32];

    // Read the data to read buffer
    ZipFile zipFile = new ZipFile(f);
    InputStream is = zipFile.getInputStream(zipFile.entries().nextElement());
    int read = is.read(readBuffer, 0, readBuffer.length);

    // Assert that whole buffer been filled. Due to openJdk choice of buffer size, read
    // never returned more than 8k of data.
    assertEquals(readBuffer.length, read);
    is.close();
    zipFile.close();
}
 
Example 5
Source File: SwingUI.java    From halfnes with GNU General Public License v3.0 6 votes vote down vote up
private List<String> listRomsInZip(String zipName) throws IOException {
    final ZipFile zipFile = new ZipFile(zipName);
    final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    final List<String> romNames = new ArrayList<>();
    while (zipEntries.hasMoreElements()) {
        final ZipEntry entry = zipEntries.nextElement();
        if (!entry.isDirectory() && (entry.getName().endsWith(".nes")
                || entry.getName().endsWith(".fds")
                || entry.getName().endsWith(".nsf"))) {
            romNames.add(entry.getName());
        }
    }
    zipFile.close();
    if (romNames.isEmpty()) {
        throw new IOException("No NES games found in ZIP file.");
    }
    return romNames;
}
 
Example 6
Source File: GrailsPluginSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public GrailsPlugin getPluginFromZipFile(String path) {
    GrailsPlugin plugin = null;
    try {
        File pluginFile = new File(path);
        if (pluginFile.exists() && pluginFile.isFile()) {
            final ZipFile file = new ZipFile(pluginFile);
            try {
                final ZipEntry entry = file.getEntry("plugin.xml"); // NOI18N
                if (entry != null) {
                    InputStream stream = file.getInputStream(entry);
                    plugin = getPluginFromInputStream(stream, pluginFile);
                }
            } finally {
                file.close();
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return plugin;
}
 
Example 7
Source File: XposedHelpers.java    From AndHook with MIT License 5 votes vote down vote up
/**
 * Invokes the {@link ZipFile#close()} method, ignoring IOExceptions.
 */
/*package*/
static void closeSilently(final ZipFile zipFile) {
    if (zipFile != null) {
        try {
            zipFile.close();
        } catch (final IOException ignored) {
        }
    }
}
 
Example 8
Source File: JarFilePackageLister.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void listJarPackages(File jarFile, JarFilePackageListener listener) {
    if (jarFile == null) {
        throw new IllegalArgumentException("jarFile is null!");
    }

    final String jarFileAbsolutePath = jarFile.getAbsolutePath();

    if (!jarFile.exists()) {
        throw new IllegalArgumentException("jarFile doesn't exists! (" + jarFileAbsolutePath + ")");
    }
    if (!jarFile.isFile()) {
        throw new IllegalArgumentException("jarFile is not a file! (" + jarFileAbsolutePath + ")");
    }
    if (!jarFile.getName().endsWith(".jar")) {
        throw new IllegalArgumentException("jarFile is not a jarFile! (" + jarFileAbsolutePath + ")");
    }

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

            while (zipFileEntries.hasMoreElements()) {
                final ZipEntry zipFileEntry = zipFileEntries.nextElement();

                if (zipFileEntry.isDirectory()) {
                    final String zipFileEntryName = zipFileEntry.getName();

                    if (!zipFileEntryName.startsWith("META-INF")) {
                        listener.receivePackage(zipFileEntryName);
                    }
                }
            }
        } finally {
            zipFile.close();
        }
    } catch (IOException e) {
        throw new GradleException("failed to scan jar file for packages (" + jarFileAbsolutePath + ")", e);
    }
}
 
Example 9
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void flush() {
	Thread currentThread = Thread.currentThread();
	Iterator iterator = this.map.values().iterator();
	while (iterator.hasNext()) {
		try {
			ZipFile zipFile = (ZipFile)iterator.next();
			if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
				System.out.println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$
			}
			zipFile.close();
		} catch (IOException e) {
			// problem occured closing zip file: cannot do much more
		}
	}
}
 
Example 10
Source File: Tools.java    From torrenttunes-client with GNU General Public License v3.0 5 votes vote down vote up
public static void unzip(File zipfile, File directory) {
	try {
		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();
				}
			}
		}

		zfile.close();


	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 11
Source File: GZipUtils.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * @param @param  unZipfile
 * @param @param  destFile 指定读取文件,需要从压缩文件中读取文件内容的文件名
 * @param @return 设定文件
 * @return String 返回类型
 * @throws
 * @Title: unZip
 * @Description: TODO(这里用一句话描述这个方法的作用)
 */
public static String unZip(String unZipfile, String destFile) {// unZipfileName需要解压的zip文件名
    InputStream inputStream;
    String inData = null;
    try {
        // 生成一个zip的文件
        File f = new File(unZipfile);
        ZipFile zipFile = new ZipFile(f);

        // 遍历zipFile中所有的实体,并把他们解压出来
        ZipEntry entry = zipFile.getEntry(destFile);
        if (!entry.isDirectory()) {
            // 获取出该压缩实体的输入流
            inputStream = zipFile.getInputStream(entry);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bys = new byte[4096];
            for (int p = -1; (p = inputStream.read(bys)) != -1; ) {
                out.write(bys, 0, p);
            }
            inData = out.toString();
            out.close();
            inputStream.close();
        }
        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return inData;
}
 
Example 12
Source File: GZipUtils.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * @param @param  unZipfile
 * @param @param  destFile 指定读取文件,需要从压缩文件中读取文件内容的文件名
 * @param @return 设定文件
 * @return String 返回类型
 * @throws
 * @Title: unZip
 * @Description: TODO(这里用一句话描述这个方法的作用)
 */
public static String unZip(String unZipfile, String destFile) {// unZipfileName需要解压的zip文件名
    InputStream inputStream;
    String inData = null;
    try {
        // 生成一个zip的文件
        File f = new File(unZipfile);
        ZipFile zipFile = new ZipFile(f);

        // 遍历zipFile中所有的实体,并把他们解压出来
        ZipEntry entry = zipFile.getEntry(destFile);
        if (!entry.isDirectory()) {
            // 获取出该压缩实体的输入流
            inputStream = zipFile.getInputStream(entry);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bys = new byte[4096];
            for (int p = -1; (p = inputStream.read(bys)) != -1; ) {
                out.write(bys, 0, p);
            }
            inData = out.toString();
            out.close();
            inputStream.close();
        }
        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return inData;
}
 
Example 13
Source File: MetaInf.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static boolean contains(File jarFile, String entryName)
    throws IOException {
    ZipFile zf = new ZipFile(jarFile);
    if ( zf != null ) {
        boolean result = zf.getEntry(entryName) != null;
        zf.close();
        return result;
    }
    return false;
}
 
Example 14
Source File: ExecutableResource.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private void unpackArchive(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        LOG.debug("Extracting archive entry: {}", entry.getName());
        File zipFileEntry = DOWNLOAD_HOME.resolve(entry.getName()).toFile();
        if (!entry.isDirectory()) {
            copyStream(zipFile.getInputStream(entry), new FileOutputStream(zipFileEntry));
        } else {
            zipFileEntry.mkdirs();
        }
    }
    zipFile.close();
}
 
Example 15
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void checkSetTime(long time) throws IOException {
  File f = createTemporaryZipFile();
  ZipOutputStream out = createZipOutputStream(f);
  ZipEntry ze = new ZipEntry("x");
  ze.setSize(0);
  ze.setTime(time);
  out.putNextEntry(ze);
  out.closeEntry();
  out.close();

  // Read it back, and check that we see the entry.
  ZipFile zipFile = new ZipFile(f);
  assertEquals(time, zipFile.getEntry("x").getTime());
  zipFile.close();
}
 
Example 16
Source File: AndroidBinaryIntegrationTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testLibraryMetadataChecksum() throws IOException {
  String target = "//apps/sample:app_cxx_lib_asset";
  workspace.runBuckCommand("build", target).assertSuccess();
  Path pathToZip =
      workspace.getPath(
          BuildTargetPaths.getGenPath(
              filesystem, BuildTargetFactory.newInstance(target), "%s.apk"));
  ZipFile file = new ZipFile(pathToZip.toFile());
  ZipEntry metadata = file.getEntry("assets/lib/metadata.txt");
  assertNotNull(metadata);

  BufferedReader contents =
      new BufferedReader(new InputStreamReader(file.getInputStream(metadata)));
  String line = contents.readLine();
  byte[] buffer = new byte[512];
  while (line != null) {
    // Each line is of the form <filename> <filesize> <SHA256 checksum>
    String[] tokens = line.split(" ");
    assertSame(tokens.length, 3);
    String filename = tokens[0];
    int filesize = Integer.parseInt(tokens[1]);
    String checksum = tokens[2];

    ZipEntry lib = file.getEntry("assets/lib/" + filename);
    assertNotNull(lib);
    InputStream is = file.getInputStream(lib);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while (filesize > 0) {
      int read = is.read(buffer, 0, Math.min(buffer.length, filesize));
      assertTrue(read >= 0);
      out.write(buffer, 0, read);
      filesize -= read;
    }
    String actualChecksum = Hashing.sha256().hashBytes(out.toByteArray()).toString();
    assertEquals(checksum, actualChecksum);
    is.close();
    out.close();
    line = contents.readLine();
  }
  file.close();
  contents.close();
}
 
Example 17
Source File: Zip.java    From DexEncryptionDecryption with Apache License 2.0 4 votes vote down vote up
/**
 * 解压zip文件至dir目录
 * @param zip
 * @param dir
 */
public static void unZip(File zip, File dir) {
    try {
        deleteFile(dir);
        ZipFile zipFile = new ZipFile(zip);
        //zip文件中每一个条目
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        //遍历
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            //zip中 文件/目录名
            String name = zipEntry.getName();
            //原来的签名文件 不需要了
            if (name.equals("META-INF/CERT.RSA") || name.equals("META-INF/CERT.SF") || name
                    .equals("META-INF/MANIFEST.MF")) {
                continue;
            }
            //空目录不管
            if (!zipEntry.isDirectory()) {
                File file = new File(dir, name);
                //创建目录
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //写文件
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = zipFile.getInputStream(zipEntry);
                byte[] buffer = new byte[2048];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        }
        zipFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: ClassFileSourceImpl.java    From cfr with MIT License 4 votes vote down vote up
private JarContent processClassPathFile(final File file, boolean dump, AnalysisType analysisType) {
    List<String> content = ListFactory.newList();
    Map<String, String> manifest;
    try {
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        manifest = getManifestContent(zipFile);
        try {
            Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
            while (enumeration.hasMoreElements()) {
                ZipEntry entry = enumeration.nextElement();
                if (!entry.isDirectory()) {
                    String name = entry.getName();
                    if (name.endsWith(".class")) {
                        if (dump) {
                            System.out.println("  " + name);
                        }
                        content.add(name);
                    } else {
                        if (dump) {
                            System.out.println("  [ignoring] " + name);
                        }
                    }
                }
            }
        } finally {
            zipFile.close();
        }
    } catch (IOException e) {
        return null;
    }
    if (analysisType == AnalysisType.WAR) {
        // Strip WEB-INF/classes from the front of class files.
        final int prefixLen = MiscConstants.WAR_PREFIX.length();
        content = Functional.map(Functional.filter(content, new Predicate<String>() {
            @Override
            public boolean test(String in) {
                return in.startsWith(MiscConstants.WAR_PREFIX);
            }
        }), new UnaryFunction<String, String>() {
            @Override
            public String invoke(String arg) {
                return arg.substring(prefixLen);
            }
        });
    }

    return new JarContentImpl(content, manifest, analysisType);
}
 
Example 19
Source File: Parse.java    From mateplus with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	long startTime = System.currentTimeMillis();
	parseOptions = new ParseOptions(args);

	SemanticRoleLabeler srl;

	if (parseOptions.useReranker) {
		srl = new Reranker(parseOptions);
		// srl =
		// Reranker.fromZipFile(zipFile,parseOptions.skipPI,parseOptions.global_alfa,parseOptions.global_aiBeam,parseOptions.global_acBeam);
	} else {
		ZipFile zipFile = new ZipFile(parseOptions.modelFile);
		srl = parseOptions.skipPD ? Pipeline.fromZipFile(zipFile,
				new Step[] { Step.ai, Step.ac })
				: parseOptions.skipPI ? Pipeline.fromZipFile(zipFile,
						new Step[] { Step.pd, Step.ai, Step.ac /*
																 * ,Step.po,
																 * Step.ao
																 */})
						: Pipeline.fromZipFile(zipFile);
		zipFile.close();
	}

	SentenceWriter writer = null;
	if (parseOptions.printXML)
		writer = new FrameNetXMLWriter(parseOptions.output);
	else
		writer = new CoNLL09Writer(parseOptions.output);

	SentenceReader reader = parseOptions.skipPI ? new SRLOnlyCoNLL09Reader(
			parseOptions.inputCorpus) : new DepsOnlyCoNLL09Reader(
			parseOptions.inputCorpus);
	int senCount = 0;
	for (Sentence s : reader) {
		senCount++;
		if (senCount % 100 == 0)
			System.out.println("Parsing sentence " + senCount);
		srl.parseSentence(s);
		if (parseOptions.writeCoref)
			writer.specialwrite(s);
		else
			writer.write(s);
	}
	writer.close();
	reader.close();
	long totalTime = System.currentTimeMillis() - startTime;
	System.out.println("Done.");
	System.out.println(srl.getStatus());
	System.out.println();
	System.out.println("Total execution time: "
			+ Util.insertCommas(totalTime) + "ms");
}
 
Example 20
Source File: Locations.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public void addFile(File file, boolean warn) {
    if (contains(file)) {
        // discard duplicates
        return;
    }

    if (! fsInfo.exists(file)) {
        /* No such file or directory exists */
        if (warn) {
            log.warning(Lint.LintCategory.PATH,
                    "path.element.not.found", file);
        }
        super.add(file);
        return;
    }

    File canonFile = fsInfo.getCanonicalFile(file);
    if (canonicalValues.contains(canonFile)) {
        /* Discard duplicates and avoid infinite recursion */
        return;
    }

    if (fsInfo.isFile(file)) {
        /* File is an ordinary file. */
        if (!isArchive(file)) {
            /* Not a recognized extension; open it to see if
             it looks like a valid zip file. */
            try {
                ZipFile z = new ZipFile(file);
                z.close();
                if (warn) {
                    log.warning(Lint.LintCategory.PATH,
                            "unexpected.archive.file", file);
                }
            } catch (IOException e) {
                // FIXME: include e.getLocalizedMessage in warning
                if (warn) {
                    log.warning(Lint.LintCategory.PATH,
                            "invalid.archive.file", file);
                }
                return;
            }
        }
    }

    /* Now what we have left is either a directory or a file name
       conforming to archive naming convention */
    super.add(file);
    canonicalValues.add(canonFile);

    if (expandJarClassPaths && fsInfo.isFile(file))
        addJarClassPath(file, warn);
}