Example usage for java.util.zip ZipInputStream getNextEntry

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

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Unzips the files from a zipfile into a directory. All of the files will be put in a single
 * direcotry. If the zipfile contains a hierarchycal structure, it will be ignored.
 * //from w  ww. j  av a  2 s  .com
 * @param zipFile
 *            The zipfile to be examined
 * @param destDir
 *            The direcotry where the extracted files will be stored.
 * @return The list of the extracted files, or null if an error occurred.
 * @throws IllegalArgumentException
 *             if the destination dir is not writeable.
 * @deprecated use Extractor.unZip instead which support complex zip structure
 */
public static List<File> unzipFlat(final File zipFile, final File destDir) {
    // if (!destDir.isDirectory())
    // throw new IllegalArgumentException("Not a directory '" + destDir.getAbsolutePath()
    // + "'");

    if (!destDir.canWrite())
        throw new IllegalArgumentException("Unwritable directory '" + destDir.getAbsolutePath() + "'");

    try {
        List<File> ret = new ArrayList<File>();
        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));

        for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
                .getNextEntry()) {
            String entryName = zipentry.getName();
            if (zipentry.isDirectory())
                continue;

            File outFile = new File(destDir, entryName);
            ret.add(outFile);
            FileOutputStream fileoutputstream = new FileOutputStream(outFile);

            org.apache.commons.io.IOUtils.copy(zipinputstream, fileoutputstream);
            fileoutputstream.close();
            zipinputstream.closeEntry();
        }

        zipinputstream.close();
        return ret;
    } catch (Exception e) {
        LOGGER.warn("Error unzipping file '" + zipFile.getAbsolutePath() + "'", e);
        return null;
    }
}

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.j av 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.glaf.core.entity.mybatis.MyBatisSessionFactory.java

public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream) {
    Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>();
    java.util.zip.ZipEntry zipEntry = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    byte tmpByte[] = null;
    try {/*from   w w w .  j a v  a  2 s .com*/
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();
            if (StringUtils.endsWith(name, "Mapper.xml")) {
                tmpByte = new byte[BUFFER];
                baos = new ByteArrayOutputStream();
                bos = new BufferedOutputStream(baos, BUFFER);
                int i = 0;
                while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) {
                    bos.write(tmpByte, 0, i);
                }
                bos.flush();
                byte[] bytes = baos.toByteArray();
                IOUtils.closeStream(baos);
                IOUtils.closeStream(baos);
                zipMap.put(zipEntry.getName(), bytes);
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(baos);
        IOUtils.closeStream(baos);
    }
    return zipMap;
}

From source file:com.bukanir.android.utils.Utils.java

public static String unzipSubtitle(String zip, String path) {
    InputStream is;/*ww  w . j a  va  2  s . c o  m*/
    ZipInputStream zis;
    try {
        String filename = null;
        is = new FileInputStream(zip);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();

            if (ze.isDirectory()) {
                File fmd = new File(path + "/" + filename);
                fmd.mkdirs();
                continue;
            }

            if (filename.endsWith(".srt") || filename.endsWith(".sub")) {
                FileOutputStream fout = new FileOutputStream(path + "/" + filename);
                while ((count = zis.read(buffer)) != -1) {
                    fout.write(buffer, 0, count);
                }
                fout.close();
                zis.closeEntry();
                break;
            }
            zis.closeEntry();
        }
        zis.close();

        File z = new File(zip);
        z.delete();

        return path + "/" + filename;

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:com.asakusafw.bulkloader.testutil.UnitTestUtil.java

public static boolean assertZipFile(File[] expectedFile, File zipFile) throws IOException {

    ZipInputStream zipIs = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry zipEntry = null;//  w  ww  .j  a v  a 2 s. c  o m
    int i = 0;
    while ((zipEntry = zipIs.getNextEntry()) != null) {
        if (zipEntry.isDirectory()) {
            continue;
        }
        i++;
        File tempFile = new File("target/asakusa-thundergate/tempdata" + String.valueOf(i));
        FileOutputStream fos = new FileOutputStream(tempFile);
        byte[] b = new byte[1024];
        while (true) {
            int read = zipIs.read(b);
            if (read == -1) {
                break;
            }
            fos.write(b, 0, read);
        }

        // ?
        if (!assertFile(expectedFile[i - 1], tempFile)) {
            tempFile.delete();
            return false;
        }

        // temp
        tempFile.delete();
    }
    return true;
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Un zip a file to a destination folder.
 * @param zipFile the zip file/* w  w  w. ja v  a 2s  . c  o m*/
 * @param outputFolder the output folder
 */
public static void unZipFile(final String zipFile, final String outputFolder) {

    LogUtil.setLogString("UnZip the File", true);
    final byte[] buffer = new byte[1024];
    int len;
    try {
        // create output directory is not exists
        final File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        // get the zip file content
        final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        final StringBuilder outFolderPath = new StringBuilder();
        final StringBuilder fileLogPath = new StringBuilder();
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
            final String fileName = zipEntry.getName();
            final File newFile = new File(
                    outFolderPath.append(outputFolder).append(File.separator).append(fileName).toString());
            LogUtil.setLogString(
                    fileLogPath.append("file unzip : ").append(newFile.getAbsoluteFile()).toString(), true);
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            final FileOutputStream fos = new FileOutputStream(newFile);

            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            fileLogPath.setLength(0);
            outFolderPath.setLength(0);
        }

        zis.closeEntry();
        zis.close();

        LogUtil.setLogString("Done", true);

    } catch (IOException ex) {
        LOGGER.error("Error in unzip file", ex);
    }
}

From source file:net.ftb.util.FileUtils.java

public static void backupExtract(String zipLocation, String outputLocation) {
    Logger.logInfo("Extracting (Backup way)");
    byte[] buffer = new byte[1024];
    ZipInputStream zis = null;
    ZipEntry ze;/*from w  w  w.  ja va2  s  .co  m*/
    try {
        File folder = new File(outputLocation);
        if (!folder.exists()) {
            folder.mkdir();
        }
        zis = new ZipInputStream(new FileInputStream(zipLocation));
        ze = zis.getNextEntry();
        while (ze != null) {
            File newFile = new File(outputLocation, ze.getName());
            newFile.getParentFile().mkdirs();
            if (!ze.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
                fos.close();
            }
            ze = zis.getNextEntry();
        }
    } catch (IOException ex) {
        Logger.logError("Error while extracting zip", ex);
    } finally {
        try {
            zis.closeEntry();
            zis.close();
        } catch (IOException e) {
        }
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zip//from ww w . ja  v a  2s.  co  m
 * @param name
 * @return
 * @throws java.io.IOException
 */
public static InputStream getFile(InputStream zip, String name) throws IOException {
    ZipInputStream in = new ZipInputStream(zip);
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String entityName = entry.getName();
        if (!entry.isDirectory() && entityName.contains(name)) {
            return in;
        }
    }
    in.close();
    return null;
}

From source file:de.uka.ilkd.key.dl.gui.initialdialog.gui.ToolInstaller.java

/**
 * @param tmp/*from ww  w .j  a  va2  s. c o m*/
 * @param
 * @throws FileNotFoundException
 * @throws IOException
 */
private static void unzip(File file, File dir, PropertySetter ps, JProgressBar bar)
        throws FileNotFoundException, IOException {
    final int BUFFER = 2048;
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(file);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    int value = 0;
    while ((entry = zis.getNextEntry()) != null) {
        bar.setValue(value++);
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        String outputFile = dir.getAbsolutePath() + File.separator + entry.getName();
        if (entry.isDirectory()) {
            new File(outputFile).mkdirs();
        } else {
            FileOutputStream fos = new FileOutputStream(outputFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
            File oFile = new File(outputFile);
            if (OSInfosDefault.INSTANCE.getOs() == OperatingSystem.OSX) {
                // FIXME: we need to make everything executable as somehow
                // the executable bit is not preserved in
                // OSX
                oFile.setExecutable(true);
            }
            if (ps.filterFilename(oFile)) {
                ps.setProperty(outputFile);
            }
        }
    }
    zis.close();
    file.delete();
}

From source file:com.edgenius.core.util.ZipFileUtil.java

public static void expandZipToFolder(InputStream is, String destFolder) throws ZipFileUtilException {
    // got our directory, so write out the input file and expand the zip file
    // this is really a hack - write it out temporarily then read it back in again! urg!!!!
    ZipInputStream zis = new ZipInputStream(is);
    int count;//from www.j ava  2 s .c  om
    byte data[] = new byte[BUFFER_SIZE];
    ZipEntry entry = null;
    BufferedOutputStream dest = null;
    String entryName = null;

    try {

        // work through each file, creating a node for each file
        while ((entry = zis.getNextEntry()) != null) {
            entryName = entry.getName();
            if (!entry.isDirectory()) {

                String destName = destFolder + File.separator + entryName;
                //It must sort out the directory information to current OS. 
                //e.g, if zip file is zipped under windows, but unzip in linux.  
                destName = FileUtil.makeCanonicalPath(destName);

                prepareDirectory(destName);

                FileOutputStream fos = new FileOutputStream(destName);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                IOUtils.closeQuietly(dest);
                dest = null;
            } else {
                String destName = destFolder + File.separator + entryName;
                destName = FileUtil.makeCanonicalPath(destName);
                new File(destName).mkdirs();
            }

        }

    } catch (IOException ioe) {

        log.error("Exception occured processing entries in zip file. Entry was " + entryName, ioe);
        throw new ZipFileUtilException(
                "Exception occured processing entries in zip file. Entry was " + entryName, ioe);

    } finally {
        IOUtils.closeQuietly(dest);
        IOUtils.closeQuietly(zis);
    }
}