
package de.ivu.elect.util;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;

public class ZipFileUtil {

  private ZipFileUtil() {
    super();
  }

  /**
   * Entpackt eine zip-Datei in das angegebene Verzeichnis.
   *
   * Siehe https://stackoverflow.com/a/13912353
   *
   * @param file
   *          zip-Datei
   * @param destinationFolder
   *          Zielverzeichnis
   * @throws IOException
   */
  public static void unzip(File file, File destinationFolder) throws IOException {
    if (destinationFolder.exists() && !destinationFolder.isDirectory()) {
      throw new IOException(destinationFolder.getAbsolutePath() + " ist kein Verzeichnis.");
    }
    ZipFile zipFile = new ZipFile(file);
    try {
      Enumeration< ? extends ZipEntry> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(destinationFolder.getAbsolutePath(), entry.getName());
        if (entry.isDirectory()) {
          entryDestination.mkdirs();
        } else {
          entryDestination.getParentFile().mkdirs();
          try (InputStream in = zipFile.getInputStream(entry);
              OutputStream out = new FileOutputStream(entryDestination)) {
            IOUtils.copy(in, out);
          }
        }
      }
    } finally {
      zipFile.close();
    }
  }
}
