0

I have a zip file which contains,

  1. war files
  2. jar files
  3. jar files may contain jar files within that.

I need to unzip a zip file which contains above-mentioned file types. Meanwhile, it should unpack all jar or war files also.

Is there any way to do this using shell script or java? else any single command to do all these.

Bhranee
  • 71
  • 1
  • 7
  • Possible duplicate of [How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?](https://stackoverflow.com/questions/1079693/how-do-you-extract-a-jar-in-a-unix-filesystem-with-a-single-command-and-specify) – Syed Waqas Bukhary Mar 23 '18 at 06:00

1 Answers1

0

Try below method:

public void unzipFile(String zipFile) throws ZipException, IOException 
{
int BUFFER = 2048;
ZipFile zip = new ZipFile(new File(zipFile));
String pathToMainFile = zipFile.substring(0, zipFile.length() - 4);
new File(pathToMainFile).mkdir();
Enumeration zipEntries = zip.entries();
while (zipEntries.hasMoreElements())
{
    ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
    String current = entry.getName();
    File dest = new File(pathToMainFile, current);
    File outerParentSt = dest.getParentFile();
    outerParentSt.mkdirs();

    if (!entry.isDirectory())
    {
        BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
        int currentByte;
        byte data[] = new byte[BUFFER];
        // write the file
        FileOutputStream fos = new FileOutputStream(dest);
        BufferedOutputStream destbuff = new BufferedOutputStream(fos,
        BUFFER);

        // r w to EOF
        while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
            destbuff.write(data, 0, currentByte);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close;
    }

    if (current.endsWith(".zip")) //or jar or war
    {
        unzipFile(dest.getAbsolutePath()); //recursively
    }
  }
}
Manvi
  • 1,136
  • 2
  • 18
  • 41
  • Thanks, How can we use java temp file for this? – Bhranee Mar 24 '18 at 09:18
  • File temp = File.createTempFile("temp-file-name", ".tmp"); //will create temp file and temp.delete(); will delete it. While looping (if current.endsWith(".tmp")){temp.delete()} will work – Manvi Mar 24 '18 at 12:44