Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

In this page you can find the example usage for java.util.zip ZipFile ZipFile.

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:net.codestory.simplelenium.driver.Downloader.java

protected void unzip(File zip, File toDir) throws IOException {
    try (ZipFile zipFile = new ZipFile(zip)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }/*from w w  w  .  ja  va2 s.co  m*/

            File to = new File(toDir, entry.getName());

            File parent = to.getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs()) {
                    throw new IOException("Unable to create folder " + parent);
                }
            }

            try (InputStream input = zipFile.getInputStream(entry)) {
                Files.copy(input, to.toPath(), REPLACE_EXISTING);
            }
        }
    }
}

From source file:forge.CardStorageReader.java

public CardStorageReader(final String cardDataDir, final CardStorageReader.ProgressObserver progressObserver,
        final Observer observer) {
    this.progressObserver = progressObserver != null ? progressObserver
            : CardStorageReader.ProgressObserver.emptyObserver;
    this.cardsfolder = new File(cardDataDir);
    this.observer = observer;

    // These read data for lightweight classes.
    if (!cardsfolder.exists()) {
        throw new RuntimeException("CardReader : constructor error -- " + cardsfolder.getAbsolutePath()
                + " file/folder not found.");
    }//  ww  w .j a  v  a 2 s.c  o  m

    if (!cardsfolder.isDirectory()) {
        throw new RuntimeException(
                "CardReader : constructor error -- not a directory -- " + cardsfolder.getAbsolutePath());
    }

    final File zipFile = new File(cardsfolder, "cardsfolder.zip");

    if (zipFile.exists()) {
        try {
            this.zip = new ZipFile(zipFile);
        } catch (final Exception exn) {
            System.err.printf("Error reading zip file \"%s\": %s. Defaulting to txt files in \"%s\".%n",
                    zipFile.getAbsolutePath(), exn, cardsfolder.getAbsolutePath());
        }
    }

    this.charset = Charset.forName(CardStorageReader.DEFAULT_CHARSET_NAME);

}

From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge//from   w w w.  j av a2 s. c o m
 * @param fileName filePath
 * @return
 */
public static int unzipCSAR(String fileName, String filePath) {
    final int BUFFER = 2048;
    int status = 0;

    try {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            //read directory as file first,so only need to create directory
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            //Because that is random to read zipfile,maybe the file is read first
            //before the directory is read,so we need to create directory first.
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bos.flush();
            bos.close();
            bis.close();

            if (entry.getName().endsWith(".zip")) {
                File subFile = new File(filePath + entry.getName());
                if (subFile.exists()) {
                    int subStatus = unzipCSAR(filePath + entry.getName(), subFile.getParent() + "/");
                    if (subStatus != 0) {
                        LOG.error("sub file unzip fail!" + subFile.getName());
                        status = Constant.UNZIP_FAIL;
                        return status;
                    }
                }
            }
        }
        status = Constant.UNZIP_SUCCESS;
        zipFile.close();
    } catch (Exception e) {
        status = Constant.UNZIP_FAIL;
        e.printStackTrace();
    }
    return status;
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();//from  w  ww .ja va 2s.  c  o m
    String outputFileName = outputFile.getAbsolutePath();

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(new ZipFileWriterSource());
    itemWriter.setup(getStepExecution(outputFileName));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:com.fujitsu.dc.core.eventlog.ArchiveLogCollection.java

/**
 * ????.//from  w  w w.  j av a 2  s.com
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:io.personium.core.eventlog.ArchiveLogCollection.java

/**
 * ????.//from   ww w.  ja  v a2 s . c om
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:com.ts.db.connector.ConnectorDriverManager.java

private static Driver getDriver(File jar, String url, ClassLoader cl) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {/*from w w  w . j  a va 2  s . c om*/
        for (ZipEntry entry : Iteration.asIterable(zipFile.entries())) {
            final String name = entry.getName();
            if (name.endsWith(".class")) {
                final String fqcn = name.replaceFirst("\\.class", "").replace('/', '.');
                try {
                    Class<?> c = DynamicLoader.loadClass(fqcn, cl);
                    if (Driver.class.isAssignableFrom(c)) {
                        Driver driver = (Driver) c.newInstance();
                        if (driver.acceptsURL(url)) {
                            return driver;
                        }
                    }
                } catch (Exception ex) {
                    if (log.isTraceEnabled()) {
                        log.trace(ex.toString());
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
    return null;
}

From source file:com.github.swt_release_fetcher.Artifact.java

public void deploy() throws IOException {
    File jarFile = null;/*  ww w  .ja va 2s. com*/
    File sourcesFile = null;
    File pomFile = null;
    ZipFile zipFile = null;

    try {
        jarFile = File.createTempFile("deploy", ".jar");
        sourcesFile = File.createTempFile("deploy", "-sources.jar");
        pomFile = File.createTempFile("pom", ".xml");

        zipFile = new ZipFile(file);
        extractFromZip(zipFile, "swt.jar", jarFile);
        extractFromZip(zipFile, "src.zip", sourcesFile);
        generatePom(pomFile);

        runMavenDeploy(pomFile, jarFile, sourcesFile);

    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
        FileUtils.deleteQuietly(jarFile);
        FileUtils.deleteQuietly(sourcesFile);
        FileUtils.deleteQuietly(pomFile);
    }
}

From source file:com.openmeap.model.ArchiveFileHelper.java

/**
 * //from   w ww.j a  v  a  2  s  .  c o  m
 * @param archive
 * @param zipFile
 * @param events
 * @return TRUE if the file successfully is exploded, FALSE otherwise.
 */
public static Boolean unzipFile(ModelManager modelManager, FileOperationManager fileManager,
        ApplicationArchive archive, File zipFile, List<ProcessingEvent> events) {
    try {
        GlobalSettings settings = modelManager.getGlobalSettings();
        File dest = archive.getExplodedPath(settings.getTemporaryStoragePath());
        if (dest.exists()) {
            fileManager.delete(dest.getAbsolutePath());
        }
        ZipFile file = null;
        try {
            file = new ZipFile(zipFile);
            fileManager.unzipFile(file, archive.getHash());
        } finally {
            file.close();
        }
        return Boolean.TRUE;
    } catch (Exception e) {
        logger.error("An exception occurred unzipping the archive to the viewing location: {}", e);
        events.add(new MessagesEvent(String.format(
                "An exception occurred unzipping the archive to the viewing location: %s", e.getMessage())));
    }
    return Boolean.FALSE;
}

From source file:apim.restful.importexport.utils.APIImportUtil.java

/**
 * This method decompresses API the archive
 *
 * @param sourceFile  The archive containing the API
 * @param destination location of the archive to be extracted
 * @return Name of the extracted directory
 * @throws APIImportException If the decompressing fails
 *///ww  w  .  j  a  v a2s  . c  o  m
public static String extractArchive(File sourceFile, String destination) throws APIImportException {

    BufferedInputStream inputStream = null;
    InputStream zipInputStream = null;
    FileOutputStream outputStream = null;
    ZipFile zip = null;
    String archiveName = null;

    try {
        zip = new ZipFile(sourceFile);
        Enumeration zipFileEntries = zip.entries();
        int index = 0;

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {

            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            //This index variable is used to get the extracted folder name; that is root directory
            if (index == 0) {
                archiveName = currentEntry.substring(0,
                        currentEntry.indexOf(APIImportExportConstants.ARCHIVE_PATH_SEPARATOR));
                --index;
            }

            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();

            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.info("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }

            if (!entry.isDirectory()) {
                zipInputStream = zip.getInputStream(entry);
                inputStream = new BufferedInputStream(zipInputStream);

                // write the current file to the destination
                outputStream = new FileOutputStream(destinationFile);
                IOUtils.copy(inputStream, outputStream);
            }
        }
        return archiveName;
    } catch (IOException e) {
        log.error("Failed to extract archive file ", e);
        throw new APIImportException("Failed to extract archive file. " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}