anujin
anujin

Reputation: 781

How to unzip a zip folder containing different file formats using Java

I need to unzip a zipped directory containing different files' format like .txt, .xml, .xls etc.

I am able to unzip if the directory contains only .txt files but it fails with other files format. Below is the program that I am using and after a bit of googling, all I saw was similar approach -

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipUtils {
  public static void extractFile(InputStream inStream, OutputStream outStream) throws IOException {
      byte[] buf = new byte[1024];
      int l;
      while ((l = inStream.read(buf)) >= 0) {
           outStream.write(buf, 0, l);
      }
      inStream.close();
      outStream.close();
  }

  public static void main(String[] args) {
      Enumeration enumEntries;
      ZipFile zip;

      try {
          zip = new ZipFile("myzip.zip");
          enumEntries = zip.entries();
          while (enumEntries.hasMoreElements()) {
              ZipEntry zipentry = (ZipEntry) enumEntries.nextElement();
              if (zipentry.isDirectory()) {
                  System.out.println("Name of Extract directory : " + zipentry.getName());
                  (new File(zipentry.getName())).mkdir();
                  continue;
              }
              System.out.println("Name of Extract fille : " + zipentry.getName());

              extractFile(zip.getInputStream(zipentry), new FileOutputStream(zipentry.getName()));
          }
          zip.close();
     } catch (IOException ioe) {
         System.out.println("There is an IoException Occured :" + ioe);
         ioe.printStackTrace();
     }
  }
}

Throws the below exception -

There is an IoException Occured :java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
    at updaterunresults.ZipUtils.main(ZipUtils.java:43)

Upvotes: 0

Views: 7284

Answers (2)

Veger
Veger

Reputation: 37915

When you try to open the file that is going to contain the extracted content, the error occurs. This is because the myzip folder is not available.

So check if it indeed is not available and create it before extracting the zip:

File outputDirectory = new File("myzip");
if(!outputDirectory.exists()){
    outputDirectory.mkdir();
}

As @Perception pointed out in the comments: The output location is relative to the active/working directory. This is probably not very convenient, so you might want to add the extraction location to the location of the extracted files:

File outputLocation = new File(outputDirectory, zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(outputLocation));

(of course you need also add outputLocation to the directory creation code)

Upvotes: 3

X-Factor
X-Factor

Reputation: 2127

This is a good example in which he showed to unzip all the formats (pdf, txt etc) have look its quite

or you can use this code might work (i haven't tried this)

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils
{
  private static final int  BUFFER_SIZE = 4096;

  private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException
  {
    byte[] buffer = new byte[BUFFER_SIZE];
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name)));
    int count = -1;
    while ((count = in.read(buffer)) != -1)
      out.write(buffer, 0, count);
    out.close();
  }

  private static void mkdirs(File outdir,String path)
  {
    File d = new File(outdir, path);
    if( !d.exists() )
      d.mkdirs();
  }

  private static String dirpart(String name)
  {
    int s = name.lastIndexOf( File.separatorChar );
    return s == -1 ? null : name.substring( 0, s );
  }

  /***
   * Extract zipfile to outdir with complete directory structure
   * @param zipfile Input .zip file
   * @param outdir Output directory
   */
  public static void extract(File zipfile, File outdir)
  {
    try
    {
      ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
      ZipEntry entry;
      String name, dir;
      while ((entry = zin.getNextEntry()) != null)
      {
        name = entry.getName();
        if( entry.isDirectory() )
        {
          mkdirs(outdir,name);
          continue;
        }
        /* this part is necessary because file entry can come before
         * directory entry where is file located
         * i.e.:
         *   /foo/foo.txt
         *   /foo/
         */
        dir = dirpart(name);
        if( dir != null )
          mkdirs(outdir,dir);

        extractFile(zin, outdir, name);
      }
      zin.close();
    } 
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

Regards

Upvotes: 2

Related Questions