-2

I'm wondering, how do you unzip a zip file in java?

I first tried:

String source = "forge.zip";
String destination = "some/destination/folder";
try {
    zipFile = new ZipFile(source);
    zipFile.extractAll(destination);
    } catch (ZipException e) {
     e.printStackTrace();
    }

It gives says that zpFile does not have an extractAll method. Is that true?

Ajay
  • 437
  • 7
  • 22

1 Answers1

1

I cannot tell what problem you're having. But I have done this before several times with ZipInputStreams and ZipEntrys, and I know this will work:

File dir = new File(destDir);

if(!dir.exists()) dir.mkdirs();
FileInputStream fis;

byte[] buffer = new byte[1024];
try {
    fis = new FileInputStream(zipFilePath);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();

    while(ze != null){
        String fileName = ze.getName();
        File newFile = new File(destDir + File.separator + fileName);

        new File(newFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(newFile);
        int len;

        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
    fis.close();

} catch (IOException e) {
    e.printStackTrace();
}
john_science
  • 6,325
  • 6
  • 43
  • 60