Home  >  Article  >  Java  >  How to Extract JAR File Contents into a Specified Directory?

How to Extract JAR File Contents into a Specified Directory?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 00:53:31436browse

How to Extract JAR File Contents into a Specified Directory?

Extracting JAR File Contents into a Specified Directory

Problem:

You have a JAR file and need to extract its contents into a specific directory. Running the "jar -xf filename.jar" command returns an error.

Solution:

Using an Existing Example:

  • Refer to this guide on extracting Java resources from JAR and ZIP archives: https://examples.javacodegeeks.com/core-java/java-util-jar-extract-resources-from-jar-and-zip-archive-example/.

Custom Code:

Alternatively, use the following code:

<code class="java">// JAR file to extract
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);

// Extract all entries
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
    // Get the entry
    java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();

    // Create a file object
    java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());

    // If the entry is a directory, create it
    if (file.isDirectory()) {
        f.mkdir();
        continue;
    }

    // Otherwise, extract the file
    java.io.InputStream is = jar.getInputStream(file); // Input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f); // Output stream

    // Write the file contents
    while (is.available() > 0) {
        fos.write(is.read());
    }

    // Close streams
    fos.close();
    is.close();
}

// Close the JAR file
jar.close();</code>

Source: http://www.devx.com/tips/Tip/22124

The above is the detailed content of How to Extract JAR File Contents into a Specified Directory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn