java.util.jar.JarFile#close ( )源码实例Demo

下面列出了java.util.jar.JarFile#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk8u-backup   文件: TestNormal.java
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
源代码2 项目: sofa-ark   文件: ArkPluginMojo.java
public void shadeJarIntoArkPlugin(File pluginFile, File tmpPluginFile, Set<Artifact> artifacts)
                                                                                               throws IOException {
    Set<Artifact> shadeJars = new HashSet<>();
    shadeJars.add(project.getArtifact());
    for (Artifact artifact : artifacts) {
        if (isShadeJar(artifact)) {
            shadeJars.add(artifact);
        }
    }

    JarWriter writer = new JarWriter(pluginFile);
    JarFile tmpJarFile = new JarFile(tmpPluginFile);
    try {
        writer.writeEntries(tmpJarFile);
        for (Artifact jar : shadeJars) {
            writer.writeEntries(new JarFile(jar.getFile()));
        }
    } finally {
        writer.close();
        tmpJarFile.close();
    }
}
 
源代码3 项目: netbeans   文件: FileUtils.java
public static File extractJarEntry(
        final String entry,
        final File source,
        final File target) throws IOException {
    JarFile jar = new JarFile(source);
    FileOutputStream out = new FileOutputStream(target);
    
    try {
        StreamUtils.transferData(jar.getInputStream(jar.getEntry(entry)), out);
        
        return target;
    } finally {
        jar.close();
        out.close();
    }
}
 
源代码4 项目: hottub   文件: PackerImpl.java
/**
 * Takes a JarFile and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 *
 * @param in  a JarFile
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarFile in, OutputStream out) throws IOException {
    assert (Utils.currentInstance.get() == null);

    boolean needUTC = !props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE);
    try {
        Utils.currentInstance.set(this);
        if (needUTC) {
            Utils.changeDefaultTimeZoneToUtc();
        }

        if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
            Utils.copyJarFile(in, out);
        } else {
            (new DoPack()).run(in, out);
        }
    } finally {
        Utils.currentInstance.set(null);
        if (needUTC) {
            Utils.restoreDefaultTimeZone();
        }
        in.close();
    }
}
 
源代码5 项目: hottub   文件: FSInfo.java
public List<File> getJarClassPath(File file) throws IOException {
    String parent = file.getParent();
    JarFile jarFile = new JarFile(file);
    try {
        Manifest man = jarFile.getManifest();
        if (man == null)
            return Collections.emptyList();

        Attributes attr = man.getMainAttributes();
        if (attr == null)
            return Collections.emptyList();

        String path = attr.getValue(Attributes.Name.CLASS_PATH);
        if (path == null)
            return Collections.emptyList();

        List<File> list = new ArrayList<File>();

        for (StringTokenizer st = new StringTokenizer(path); st.hasMoreTokens(); ) {
            String elt = st.nextToken();
            File f = (parent == null ? new File(elt) : new File(parent, elt));
            list.add(f);
        }

        return list;
    } finally {
        jarFile.close();
    }
}
 
源代码6 项目: JByteMod-Beta   文件: JarUtils.java
/**
 * Creates a map of <String(Class name), ClassNode> for a given jar file
 * 
 * @param jarFile
 * @author Konloch (Bytecode Viewer)
 * @return
 * @throws IOException
 */
public static Map<String, ClassNode> loadClasses(File jarFile) throws IOException {
  Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
  JarFile jar = new JarFile(jarFile);
  Stream<JarEntry> str = jar.stream();
  // For some reason streaming = entries in messy jars
  // enumeration = no entries
  // Or if the jar is really big, enumeration = infinite hang
  // ...
  // Whatever. It works now!
  str.forEach(z -> readJar(jar, z, classes, null));
  jar.close();
  return classes;
}
 
源代码7 项目: hadoop   文件: RunJar.java
/**
 * Unpack matching files from a jar. Entries inside the jar that do
 * not match the given pattern will be skipped.
 *
 * @param jarFile the .jar file to unpack
 * @param toDir the destination directory into which to unpack the jar
 * @param unpackRegex the pattern to match jar entries against
 */
public static void unJar(File jarFile, File toDir, Pattern unpackRegex)
  throws IOException {
  JarFile jar = new JarFile(jarFile);
  try {
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
      final JarEntry entry = entries.nextElement();
      if (!entry.isDirectory() &&
          unpackRegex.matcher(entry.getName()).matches()) {
        InputStream in = jar.getInputStream(entry);
        try {
          File file = new File(toDir, entry.getName());
          ensureDirectory(file.getParentFile());
          OutputStream out = new FileOutputStream(file);
          try {
            IOUtils.copyBytes(in, out, 8192);
          } finally {
            out.close();
          }
        } finally {
          in.close();
        }
      }
    }
  } finally {
    jar.close();
  }
}
 
源代码8 项目: hottub   文件: Utils.java
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je : Collections.list(in.entries())) {
        out.putNextEntry(je);
        InputStream ein = in.getInputStream(je);
        for (int nr; 0 < (nr = ein.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
源代码9 项目: netbeans   文件: WLPluginProperties.java
public static Version getServerVersion(File serverRoot) {
    File weblogicJar = WebLogicLayout.getWeblogicJar(serverRoot);
    if (!weblogicJar.exists()) {
        return null;
    }
    try {
        // JarInputStream cannot be used due to problem in weblogic.jar in Oracle Weblogic Server 10.3
        JarFile jar = new JarFile(weblogicJar);
        try {
            Manifest manifest = jar.getManifest();
            String implementationVersion = null;
            if (manifest != null) {
                implementationVersion = manifest.getMainAttributes()
                        .getValue("Implementation-Version"); // NOI18N
            }
            if (implementationVersion != null) { // NOI18N
                implementationVersion = implementationVersion.trim();
                return Version.fromJsr277OrDottedNotationWithFallback(implementationVersion);
            }
        } finally {
            try {
                jar.close();
            } catch (IOException ex) {
                LOGGER.log(Level.FINEST, null, ex);
            }
        }
    } catch (IOException e) {
        LOGGER.log(Level.FINE, null, e);
    }
    return null;
}
 
源代码10 项目: fdroidclient   文件: IndexV1Updater.java
private void processDownloadedIndex(File outputFile, String cacheTag)
        throws IOException, IndexUpdater.UpdateException {
    JarFile jarFile = new JarFile(outputFile, true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(DATA_FILE_NAME);
    InputStream indexInputStream = new ProgressBufferedInputStream(jarFile.getInputStream(indexEntry),
            processIndexListener, (int) indexEntry.getSize());
    processIndexV1(indexInputStream, indexEntry, cacheTag);
    jarFile.close();
}
 
源代码11 项目: snap-desktop   文件: ModulePackager.java
public static String getAdapterAlias(File jarFile) throws IOException {
    String version = null;
    JarFile jar = new JarFile(jarFile);
    Attributes attributes = jar.getManifest().getMainAttributes();
    if (attributes.containsKey(ATTR_MODULE_ALIAS)) {
        version = attributes.getValue(ATTR_MODULE_ALIAS);
    }
    jar.close();
    return version;
}
 
源代码12 项目: JByteMod-Beta   文件: JarUtils.java
public static Map<String, ClassNode> loadRT() throws IOException {
  Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
  JarFile jar = new JarFile(getRT());
  Stream<JarEntry> str = jar.stream();
  // TODO: Make ignoring these packages optional
  str.forEach(z -> readJar(jar, z, classes, Arrays.asList("com/sun/", "com/oracle/", "jdk/", "sun/")));
  jar.close();
  return classes;
}
 
源代码13 项目: openjdk-jdk8u   文件: Utils.java
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je : Collections.list(in.entries())) {
        out.putNextEntry(je);
        InputStream ein = in.getInputStream(je);
        for (int nr; 0 < (nr = ein.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
源代码14 项目: jdk8u-dev-jdk   文件: URLClassPath.java
static JarFile checkJar(JarFile jar) throws IOException {
    if (System.getSecurityManager() != null && !DISABLE_JAR_CHECKING
        && !zipAccess.startsWithLocHeader(jar)) {
        IOException x = new IOException("Invalid Jar file");
        try {
            jar.close();
        } catch (IOException ex) {
            x.addSuppressed(ex);
        }
        throw x;
    }

    return jar;
}
 
源代码15 项目: scar   文件: Jar.java
static public void addToJAR (String inJar, String outJar, String addName, byte[] bytes, boolean overwrite) throws IOException {
	if (DEBUG) debug("scar", "Adding to JAR: " + inJar + " -> " + outJar + ", " + addName);

	JarFile inJarFile = new JarFile(inJar);
	mkdir(parent(outJar));
	JarOutputStream outJarStream = new JarOutputStream(new FileOutputStream(outJar));
	outJarStream.setLevel(Deflater.BEST_COMPRESSION);
	ArrayList<String> names = new ArrayList();
	for (Enumeration<JarEntry> entries = inJarFile.entries(); entries.hasMoreElements();)
		names.add(entries.nextElement().getName());

	addName = addName.replace('\\', '/');
	boolean exists = names.contains(addName) || names.contains(addName.replace('/', '\\'));
	if (!overwrite && exists) throw new RuntimeException("JAR already has entry: " + addName);
	if (!exists) {
		names.add(addName);
		Collections.sort(names);
	}

	if (names.remove("META-INF/MANIFEST.MF") || names.remove("META-INF\\MANIFEST.MF")) names.add(0, "META-INF/MANIFEST.MF");

	for (String name : names) {
		outJarStream.putNextEntry(new JarEntry(name.replace('\\', '/')));
		if (name.replace('\\', '/').equals(addName))
			outJarStream.write(bytes);
		else
			copyStream(inJarFile.getInputStream(inJarFile.getEntry(name)), outJarStream);
		outJarStream.closeEntry();
	}
	outJarStream.close();
	inJarFile.close();
}
 
源代码16 项目: xenqtt   文件: XenqttUtil.java
private static void findFilesInJar(String jarPath, ClassPathFileListBuilder builder) throws Exception {

		JarFile jarFile = new JarFile(jarPath);
		try {
			Enumeration<JarEntry> entries = jarFile.entries();
			while (entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				builder.accept(entry.getName());
			}
		} finally {
			jarFile.close();
		}
	}
 
源代码17 项目: netbeans   文件: FileUtils.java
public static boolean isSigned(
        final File file) throws IOException {
    JarFile jar = new JarFile(file);

    try {
        Enumeration<JarEntry> entries = jar.entries();
        boolean signatureInfoPresent = false;
        boolean signatureFilePresent = false;
        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement().getName();
            if (entryName.startsWith("META-INF/")) {
                if (entryName.endsWith(".RSA") || entryName.endsWith(".DSA")) {
                    signatureFilePresent = true;
                    if(signatureInfoPresent) {
                        break;
                    }
                } else if (entryName.endsWith(".SF")) {
                    signatureInfoPresent = true;
                    if(signatureFilePresent) {
                        break;
                    }
                }
            }
        }
        return signatureFilePresent && signatureInfoPresent;
    } finally {
        jar.close();
    }
}
 
源代码18 项目: pushfish-android   文件: TestFile.java
public Manifest getManifest() {
    assertIsFile();
    try {
        JarFile jarFile = new JarFile(this);
        try {
            return jarFile.getManifest();
        } finally {
            jarFile.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码19 项目: zelixkiller   文件: JarUtils.java
/**
 * Creates a map of <String(Class name), ClassNode> for a given jar file
 * 
 * @param jarFile
 * @author Konloch (Bytecode Viewer)
 * @return
 * @throws IOException
 */
public static Map<String, ClassNode> loadClasses(File jarFile) throws IOException {
	Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
	JarFile jar = new JarFile(jarFile);
	Stream<JarEntry> str = jar.stream();
	// For some reason streaming = entries in messy jars
	// enumeration = no entries
	// Or if the jar is really big, enumeration = infinite hang
	// ...
	// Whatever. It works now!
	str.forEach(z -> readJar(jar, z, classes, null));
	jar.close();
	return classes;
}
 
源代码20 项目: buck   文件: DefaultJarContentHasherTest.java
@Test
public void testGetContentHashesDoesNotIncorrectlyCache() throws Exception {
  if (Platform.isWindows()) {
    // Windows doesn't allow clobbering a file while it's already open, so this test isn't
    // meaningful for windows platforms
    return;
  }
  ProjectFilesystem filesystem =
      TestProjectFilesystems.createProjectFilesystem(temporaryFolder.getRoot().toPath());
  File toTest = temporaryFolder.newFile();
  File modification = temporaryFolder.newFile();
  new JarBuilder()
      .setShouldHashEntries(true)
      .addEntry(
          new JarEntrySupplier(
              new CustomZipEntry("Before"),
              "container_test",
              () -> new ByteArrayInputStream("Before".getBytes(StandardCharsets.UTF_8))))
      .createJarFile(toTest.toPath());
  new JarBuilder()
      .setShouldHashEntries(true)
      .addEntry(
          new JarEntrySupplier(
              new CustomZipEntry("After"),
              "container_test",
              () -> new ByteArrayInputStream("After".getBytes(StandardCharsets.UTF_8))))
      .createJarFile(modification.toPath());

  FileTime hardcodedTime = FileTime.fromMillis(ZipConstants.getFakeTime());
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);
  Files.setLastModifiedTime(modification.toPath(), hardcodedTime);

  Path relativeToTestPath = temporaryFolder.getRoot().toPath().relativize(toTest.toPath());

  // Use JarBuilder with toTest -- we cache the open file to make sure it stays mmapped
  //noinspection unused
  JarFile cache = new JarFile(toTest);
  assertThat(
      new DefaultJarContentHasher(filesystem, relativeToTestPath).getContentHashes().keySet(),
      Matchers.contains(Paths.get("Before")));

  // Now modify toTest make sure we don't get a cached result when we open it for a second time
  Files.move(modification.toPath(), toTest.toPath(), StandardCopyOption.REPLACE_EXISTING);
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);
  assertThat(
      new DefaultJarContentHasher(filesystem, relativeToTestPath).getContentHashes().keySet(),
      Matchers.contains(Paths.get("After")));
  cache.close();
}