Java ZipInputStream uncompress zip file

Description

Java ZipInputStream uncompress zip file


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

public class Main {
  public static void main(String[] args) {
    String zipFileName = "ziptest.zip";
    String unzipdirectory = "extracted";

    try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(
        new FileInputStream(zipFileName)))) {
      ZipEntry entry = null;/* w  ww  .j  a v a 2 s. c o  m*/
      while ((entry = zis.getNextEntry()) != null) {
        extractEntryContent(zis, entry, unzipdirectory);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void extractEntryContent(ZipInputStream zis, ZipEntry entry,
      String unzipdir) throws IOException, FileNotFoundException {

    String entryFileName = entry.getName();
    String entryPath = unzipdir + File.separator + entryFileName;

    File file = new File(entryPath);
    File parent = file.getParentFile();

    if (!parent.exists()) {
      parent.mkdirs();
    }
    file.createNewFile();

    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(
        entryPath));

    byte[] buffer = new byte[1024];
    int count = -1;
    while ((count = zis.read(buffer)) != -1) {
      bos.write(buffer, 0, count);
    }

    bos.close();
  }
}



PreviousNext

Related