Wednesday, February 16, 2011

How to Extract ZIP/JAR/WAR/TAR/RAR file Using Java

Extracting ZIP/JAR/WAR/TAR/RAR file using java

Using ZipEntry and ZipInputstream classes we can extract the zip/jar/war/tar files.

here is the code snippet....


 public static void extractZipFiles(String filename) {
   try {
             // destination folder to extract the contents         
             String destinationname = "d:\\temp\\testZip\\";          

             byte[] buf = new byte[1024];
             ZipInputStream zipinputstream = null;
             ZipEntry zipentry;
             zipinputstream = new ZipInputStream(new FileInputStream(filename));
            zipentry = zipinputstream.getNextEntry();
 
           while (zipentry != null) {

                 // for each entry to be extracted
                 String entryName = zipentry.getName();
    
                 int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);

              String directory = newFile.getParent();

              // to creating the parent directories
              if (directory == null) {
                   if (newFile.isDirectory()){
                         break;
                      }
             } else {
                 new File(destinationname+directory).mkdirs();
              }
    

            if(!zipentry.isDirectory()){
                       System.out.println("File to be extracted....."+ entryName);
                       fileoutputstream = new FileOutputStream(destinationname  + entryName);
                      while ((n = zipinputstream.read(buf, 0, 1024)) > -1){
                              fileoutputstream.write(buf, 0, n);
                       }
                      fileoutputstream.close();
            }
             
           zipinputstream.closeEntry();
           zipentry = zipinputstream.getNextEntry();
          }// while
  
     zipinputstream.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

...

6 comments:

  1. Thanks dude. This helps me in very critical time.

    ReplyDelete
  2. This way is only used for extract zip file

    ReplyDelete
  3. What bout .7z files?

    ReplyDelete
  4. does it work for rar?

    ReplyDelete
  5. It seems like its only works for *.zip files

    ReplyDelete