• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to extract subdirectories with java.util.zip

 
Robert Jaeger
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I�m using the java.util.zip package to extract zip-files.
I found a lot of documentation and descriptions ... the extraction works.
Unfortunately this is only the case for files in the main directory of the zip-file, subdirectories cannot be extracted ...
... or maybe someone has an idea, that would be great

Regards,
Robert.
 
satish sathineni
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this code should solve ur problem...

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;

/**
* -----------------------------------------------------------------------------
* Used to provide an example of extracting the contents (files) from a zip
* file.
* -----------------------------------------------------------------------------
*/

public class UnzipFile {

private static void doUnzipFiles(String zipFileName) {

try {

ZipFile zf = new ZipFile(zipFileName);

System.out.println("Archive: " + zipFileName);

// Enumerate each entry
for (Enumeration entries = zf.entries(); entries.hasMoreElements() {

// Get the entry and its name
ZipEntry zipEntry = (ZipEntry)entries.nextElement();
String zipEntryName = zipEntry.getName();
System.out.println(" inflating: " + zipEntryName);

OutputStream out = new FileOutputStream(zipEntryName);
InputStream in = zf.getInputStream(zipEntry);

byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}

// Close streams
out.close();
in.close();
}

} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}

}


/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {

if (args.length != 1) {
System.err.println("Usage: java UnzipFile zipfilename");
} else {
doUnzipFiles(args[0]);
}

}

}



Have Fun ....

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic