Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:io.vertx.config.vault.utils.VaultDownloader.java

private static void unzip(File zipFilePath, File destDir) throws IOException {
    if (!destDir.exists()) {
        destDir.mkdir();/*w  w w  . j  a v a2  s .  com*/
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = destDir.getAbsolutePath() + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:net.daboross.bukkitdev.skywars.world.WorldUnzipper.java

public void doWorldUnzip(Logger logger) throws StartupFailedException {
    Validate.notNull(logger, "Logger cannot be null");
    Path outputDir = Bukkit.getWorldContainer().toPath().resolve(Statics.BASE_WORLD_NAME);
    if (Files.exists(outputDir)) {
        return;// w w w. j a  v  a 2 s . c o m
    }
    try {
        Files.createDirectories(outputDir);
    } catch (IOException e) {
        throw new StartupFailedException("Couldn't create directory " + outputDir.toAbsolutePath() + ".");
    }

    InputStream fis = WorldUnzipper.class.getResourceAsStream(Statics.ZIP_FILE_PATH);
    if (fis == null) {
        throw new StartupFailedException("Couldn't get resource.\nError creating world. Please delete "
                + Statics.BASE_WORLD_NAME + " and restart server.");
    }
    try {
        try (ZipInputStream zis = new ZipInputStream(fis)) {
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();
                Path newFile = outputDir.resolve(fileName);
                Path parent = newFile.getParent();
                if (parent != null) {
                    Files.createDirectories(parent);
                }
                if (ze.isDirectory()) {
                    logger.log(Level.FINER, "Making dir {0}", newFile);
                    Files.createDirectories(newFile);
                } else if (Files.exists(newFile)) {
                    logger.log(Level.FINER, "Already exists {0}", newFile);
                } else {
                    logger.log(Level.FINER, "Copying {0}", newFile);
                    try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
                        try {
                            int next;
                            while ((next = zis.read()) != -1) {
                                fos.write(next);
                            }
                            fos.flush();
                        } catch (IOException ex) {
                            logger.log(Level.WARNING, "Error copying file from zip", ex);
                            throw new StartupFailedException("Error creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.");
                        }
                        fos.close();
                    }
                }
                try {
                    ze = zis.getNextEntry();
                } catch (IOException ex) {
                    throw new StartupFailedException(
                            "Error getting next zip entry\nError creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.",
                            ex);
                }
            }
        }
    } catch (IOException | RuntimeException ex) {
        throw new StartupFailedException(
                "\nError unzipping world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.",
                ex);
    }
}

From source file:io.github.tsabirgaliev.ZipperInputStreamTest.java

public void testJDKCompatibility() throws IOException {
    ZipperInputStream lzis = new ZipperInputStream(enumerate(file1, file2));

    ZipInputStream zis = new ZipInputStream(lzis);

    {//from  w w  w.  java 2s  .c  o m
        ZipEntry entry1 = zis.getNextEntry();

        assert file1.getPath().equals(entry1.getName());

        assert IOUtils.contentEquals(zis, file1.getStream());

        zis.closeEntry();
    }

    {
        ZipEntry entry2 = zis.getNextEntry();

        assert file2.getPath().equals(entry2.getName());

        assert IOUtils.contentEquals(zis, file2.getStream());

        zis.closeEntry();
    }

}

From source file:com.worldline.easycukes.commons.helpers.FileHelper.java

/**
 * Extracts the content of a zip folder in a specified directory
 *
 * @param from a {@link String} representation of the URL containing the zip
 *             file to be unzipped/*from  ww w  . ja  v a 2s.c o  m*/
 * @param to   the path on which the content should be extracted
 * @throws IOException if anything's going wrong while unzipping the content of the
 *                     provided zip folder
 */
public static void unzip(@NonNull String from, @NonNull String to, boolean isRemote) throws IOException {
    @Cleanup
    ZipInputStream zip = null;
    if (isRemote)
        zip = new ZipInputStream(new FileInputStream(from));
    else
        zip = new ZipInputStream(FileHelper.class.getResourceAsStream(from));
    log.debug("Extracting zip from: " + from + " to: " + to);
    // Extract without a container directory if exists
    ZipEntry entry = zip.getNextEntry();
    String rootDir = "/";
    if (entry != null)
        if (entry.isDirectory())
            rootDir = entry.getName();
        else {
            final String filePath = to + entry.getName();
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        }
    zip.closeEntry();
    entry = zip.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String entryName = entry.getName();
        if (entryName.startsWith(rootDir))
            entryName = entryName.replaceFirst(rootDir, "");
        final String filePath = to + "/" + entryName;
        if (!entry.isDirectory())
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        else {
            // if the entry is a directory, make the directory
            final File dir = new File(filePath);
            dir.mkdir();
        }
        zip.closeEntry();
        entry = zip.getNextEntry();
    }
    // delete the zip file if recovered from URL
    if (isRemote)
        new File(from).delete();
}

From source file:com.jaromin.alfresco.repo.content.transform.ZipFormatContentTransformer.java

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {

    ZipInputStream zip = new ZipInputStream(reader.getContentInputStream());
    OutputStream out = writer.getContentOutputStream();
    try {//from  w w  w.  j  av  a  2 s  . c om
        extractEntry(this.getZipEntryPath(), zip, out);
    } finally {
        // Close the streams...
        IOUtils.closeQuietly(zip);
        IOUtils.closeQuietly(out);
    }

}

From source file:com.sonatype.nexus.repository.nuget.internal.odata.NugetPackageUtils.java

private static byte[] extractNuspec(final InputStream is) {
    try {/*from www  .  j  av a2 s  . c om*/
        ZipInputStream zis = new ZipInputStream(is);
        for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) {
            if (e.getName().endsWith(".nuspec")) {
                return ByteStreams.toByteArray(zis);
            }
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    throw new RuntimeException("Missing nuspec");
}

From source file:com.btmatthews.leabharlann.service.impl.ZipFileImportSource.java

/**
 * Initialize the import tool with an input stream.
 *
 * @param inputStream The input stream used to read the ZIP archive contents.
 *//*from   www . j  a v  a2  s  .  c o  m*/
public ZipFileImportSource(final InputStream inputStream) {
    zipInputStream = new ZipInputStream(inputStream);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.dao.DaoUtilsTest.java

@SuppressWarnings("resource")
@Test/*from   w w w.jav a  2 s. c  om*/
public void testZipFolder() {

    File toBeZippedFiles = new File("src/test/resources");
    File zipedFiles = new File("target/" + toBeZippedFiles.getName() + ".zip");
    try {
        ZipUtils.zipFolder(toBeZippedFiles, zipedFiles);
    } catch (Exception e) {
        LOG.info("Zipping fails" + ExceptionUtils.getRootCauseMessage(e));
    }

    FileInputStream fs;
    try {
        fs = new FileInputStream(zipedFiles);
        ZipInputStream zis = new ZipInputStream(fs);
        ZipEntry zE;
        while ((zE = zis.getNextEntry()) != null) {
            for (File toBeZippedFile : toBeZippedFiles.listFiles()) {
                if ((FilenameUtils.getBaseName(toBeZippedFile.getName()))
                        .equals(FilenameUtils.getBaseName(zE.getName()))) {
                    // Extract the zip file, save it to temp and compare
                    ZipFile zipFile = new ZipFile(zipedFiles);
                    ZipEntry zipEntry = zipFile.getEntry(zE.getName());
                    InputStream is = zipFile.getInputStream(zipEntry);
                    File temp = File.createTempFile("temp", ".txt");
                    OutputStream out = new FileOutputStream(temp);
                    IOUtils.copy(is, out);
                    FileUtils.contentEquals(toBeZippedFile, temp);
                }
            }
            zis.closeEntry();
        }
    } catch (FileNotFoundException e) {
        LOG.info("zipped file not found " + ExceptionUtils.getRootCauseMessage(e));
    } catch (IOException e) {
        LOG.info("Unable to get file " + ExceptionUtils.getRootCauseMessage(e));
    }

}

From source file:com.wavemaker.tools.project.upgrade.five_dot_zero.WebXmlUpgradeTask.java

@Override
public void doUpgrade(Project project, UpgradeInfo upgradeInfo) {

    File webXml = project.getWebXmlFile();
    if (webXml.exists()) {
        try {//from   w w w . j  a  v  a  2  s  .c o  m
            File webXmlBak = project.getWebInfFolder().getFile(WEB_XML_BACKUP);
            webXmlBak.getContent().write(webXml);
            webXml.delete();
            File userWebXml = project.getWebInfFolder().getFile(ProjectConstants.USER_WEB_XML);
            InputStream resourceStream = this.getClass().getClassLoader()
                    .getResourceAsStream(ProjectManager._TEMPLATE_APP_RESOURCE_NAME);
            ZipInputStream resourceZipStream = new ZipInputStream(resourceStream);

            ZipEntry zipEntry = null;

            while ((zipEntry = resourceZipStream.getNextEntry()) != null) {
                if ("webapproot/WEB-INF/user-web.xml".equals(zipEntry.getName())) {
                    Writer writer = userWebXml.getContent().asWriter();
                    IOUtils.copy(resourceZipStream, writer);
                    writer.close();
                }
            }

            resourceZipStream.close();
            resourceStream.close();
        } catch (IOException e) {
            throw new WMRuntimeException(e);
        }

        upgradeInfo.addMessage("The web.xml file has changed.  If you have custom"
                + "modifications, please copy them from " + WEB_XML_BACKUP + " to the new user-web.xml.");
    }
}

From source file:com.espringtran.compressor4j.processor.LzmaProcessor.java

/**
 * Read from compressed file/*  w w  w  .ja  v  a 2 s .co  m*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    LZMACompressorInputStream cis = new LZMACompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}