0

I have a silly problem i haven't been able to figure out. Can anyone help me? My Code is as:

String zipname = "C:/1100.zip";
    String output = "C:/1100";
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        ZipFile zipFile = new ZipFile(zipname);
        Enumeration<?> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
            System.out.println("Unzipping: " + zipEntry.getName());
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            int size;
            byte[] buffer = new byte[2048];

It doesn't create a folder but debugging shows all the contents being generated. In Order to create a folder i used the code

if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception

            bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
            while ((size = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        bos.flush();
        bos.close();
        bis.close();
    }

My zip file contains images: a.jpg b.jpg... and in the same hierarchy, I have abc.xml. I need to extract the content as is in the zip file. Any helps here.

Antoine
  • 5,158
  • 1
  • 24
  • 37
Robin
  • 128
  • 1
  • 2
  • 13

1 Answers1

0

There are a few problems with your code: Where is outPut declared? output is not a file but a string, so exists() and mkdir() do not exist. Start by declaring output like:

File output = new File("C:/1100");

Furthermore, outPut (with big P) is not declared. It be something like output + File.seprator + zipEntry.getName().

 bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));

Note that you don't need to pass a File to FileOutputStream, as constructors show in the documentation.

At this point, your code should work if your Zip file does not contain directory. However, when opening the output stream, if zipEntry.getName() has a directory component (for instance somedir/filename.txt), opening the stream will result in a FileNotFoundException, as the parent directory of the file you try to create does not exist. If you want to be able to handle such zip files, you will find your answer in: How to unzip files recursively in Java?

Community
  • 1
  • 1
Antoine
  • 5,158
  • 1
  • 24
  • 37
  • Finally i wrote it for my blog: http://thaparobin.blogspot.com/2011/11/java-unpack-zip-file-from-remote-url.html – Robin Nov 05 '11 at 06:13