I am trying to unzip files created using WinZip. The zip archives with single files are unzipped successfully but when there are subfolders in the .zip file, i am getting errors: ------------------------------------------- import java.io.*; import java.util.*; import java.util.zip.*;
public class Unzip { public static final void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while((len = in.read(buffer)) >= 0) out.write(buffer, 0, len); in.close(); out.close(); } public static final void main(String[] args) { Enumeration entries; ZipFile zipFile; if(args.length != 1) { System.err.println("Usage: Unzip zipfile"); return; } try { zipFile = new ZipFile(args[0]); entries = zipFile.entries(); while(entries.hasMoreElements()) { ZipEntry entry = (ZipEntry)entries.nextElement(); if(entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(entry.getName()))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } } } -----------------------------------------------
I tested this on my PC and I noticed something that I believe is the source of your problem. I had a zip file that contained the following structure: root_dir |--dir1 |--dir2 \--dir3 dir1, dir2, and dir3 contained files. The problem I encountered was that it first tried to create the directory "root_dir\dir2", but "root_dir" wasn't created yet so the mkdir() function returned false. Consequently, the FileOutputStream failed because the directory was never created. Print out the return value of mkdir() and you'll probably see that it returned false. I don't believe that the ZipFile.entries() returns the entries in any order. Also depending on the platform you are running on, you may need to address the fact the ZipEntry.getName() uses "/" as a file separator.
Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"
karl koch
Ranch Hand
Joined: May 25, 2001
Posts: 388
posted
0
hi
as a qick and dirty solution you could just get the parent of every file (this should always be a directory ?) and and call mkdirs() on it. maybe this works. k