f-angi
4/14/2016 - 3:56 PM

Extracts a zip file using apache commmons compress

Extracts a zip file using apache commmons compress

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

String dirName = path + File.separator + FilenameUtils.getBaseName(file.getName());
File dir = new File(dirName);
if (dir.exists()) {
    LOGGER.error("Il file {} è già stato estratto", file.getAbsolutePath());
    continue;
}
if (!dir.mkdir()) {
    LOGGER.error("Impossibile creare la directory {}", dir.getAbsolutePath());
    continue;
}

ZipFile zipFile = null;
try {

    zipFile = new ZipFile(file);
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
        InputStream in = zipFile.getInputStream(entry);
        OutputStream out = new FileOutputStream(dir);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        out.close();
    }
}
catch (ZipException e) {
    LOGGER.error(String.format("Errori durante l'estrazione del file %s", file.getAbsolutePath()), e);
}
catch (IOException e) {
    LOGGER.error(String.format("Errori durante l'estrazione del file %s", file.getAbsolutePath()), e);
}
finally {
    if (zipFile != null) {
        try {
            zipFile.close();
        }
        catch (IOException e) {
            LOGGER.error(String.format("Errori durante la chiusura del file zip %s", file.getAbsolutePath()), e);
        }
    }
}