Extracting a zip file containing a jar file in Java

1.3k views Asked by At

I want to extract a zip file which contains a jar file. This file has complex folder structure and in one of the folders there is a jar file. When I am trying to use the following code to extract the jar file the program goes in infinite loop in reading the jar file and never recovers. It keeps on writing the contents of the jar till we reach the limit of the disc space even though the jar is of only a few Mbs.

Please find the code snippet below

`

    // using a ZipInputStream to get the zipIn by passing the zipFile as FileInputStream    
    ZipEntry entry = zipIn.getNextEntry();
    String fileName= entry.getName()
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
    byte[] bytesIn = new byte[(int)bufferSize];
    while (zipIn.read(bytesIn) > 0) // This is the part where the loop does not end
    {
        bos.write(bytesIn);
    }
    ..
    // flushing an closing the bos

Please let me know if there is any way we can avoid this and get the jar file out at required location.

1

There are 1 answers

0
Steffen On BEST ANSWER

Does this suit your needs?

public static void main(String[] args) {
    try {
        copyJarFromZip("G:\\Dateien\\Desktop\\Desktop.zip",
                       "G:\\Dateien\\Desktop\\someJar.jar");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public static void copyJarFromZip(final String zipPath, final String targetPath) throws IOException {
    try (ZipFile zipFile = new ZipFile(zipPath)) {
        for (final Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry zipEntry = e.nextElement();
            if (zipEntry.getName().endsWith(".jar")) {
                Files.copy(zipFile.getInputStream(zipEntry), Paths.get(targetPath),
                           StandardCopyOption.REPLACE_EXISTING);
            }
        }
    }
}