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:Main.java

public static byte[] readBytesFormZipFile(String fileName, String fname) {
    byte[] bytes = null;
    ByteArrayOutputStream os = null;
    ZipInputStream in = null;
    try {/*from  w ww .jav a  2s . c o m*/
        os = new ByteArrayOutputStream(4096);
        in = new ZipInputStream(new FileInputStream(fileName));
        boolean found = false;
        while (!found) {
            ZipEntry entry = in.getNextEntry();
            if (fname.equalsIgnoreCase(entry.getName())) {
                found = true;
            }
        }
        int read;
        byte[] buffer = new byte[4096];
        while ((read = in.read(buffer)) >= 0) {
            os.write(buffer, 0, read);
        }
        bytes = os.toByteArray();
    } catch (Exception e) {
        bytes = null;
    } finally {
        try {
            if (os != null) {
                os.flush();
                os = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
        } catch (Exception e) {
        }
    }

    return bytes;
}

From source file:cc.recommenders.utils.Zips.java

public static void unzip(File source, File dest) throws IOException {
    ZipInputStream zis = null;
    try {//from w ww  .j av a 2s. c  o  m
        InputSupplier<FileInputStream> fis = Files.newInputStreamSupplier(source);
        zis = new ZipInputStream(fis.getInput());
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final File file = new File(dest, entry.getName());
                Files.createParentDirs(file);
                Files.write(ByteStreams.toByteArray(zis), file);
            }
        }
    } finally {
        Closeables.closeQuietly(zis);
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Extract the given ZIP file into the given destination folder.
 * //  w  w w  . ja  va  2 s.c o m
 * @param zipFile
 *            file to extract
 *            
 * @param baseFolder
 *            destination folder to extract in
 */
public static void extractZipToFolder(File zipFile, File baseFolder) {
    try {
        byte[] buf = new byte[1024];

        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            // for each entry to be extracted
            String entryName = zipentry.getName();

            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);

            int numBytes;
            FileOutputStream fileoutputstream;
            File newFile = new File(baseFolder, entryName);
            if (zipentry.isDirectory()) {
                if (!newFile.mkdirs()) {
                    break;
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            fileoutputstream = new FileOutputStream(newFile);
            while ((numBytes = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, numBytes);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/** Return true if this file is a zip file. */
public static boolean isZip(File file) throws IOException {
    if (file.exists() == false)
        return false;

    InputStream in = null;/*  w  ww.  j  av a  2 s .  c  o m*/
    try {
        in = new FileInputStream(file);
        ZipInputStream zipIn = new ZipInputStream(in);
        ZipEntry e = zipIn.getNextEntry();
        if (e == null)
            return false;
        int ctr = 0;
        while (e != null && ctr < 4) {
            e = zipIn.getNextEntry();
            ctr++;
        }
        return true;
    } catch (Throwable t) {
        return false;
    } finally {
        try {
            in.close();
        } catch (Throwable t) {
        }
    }
}

From source file:com.jlgranda.fede.ejb.url.reader.FacturaElectronicaURLReader.java

/**
 * Obtiene la lista de objetos factura para el sujeto en fede
 *
 * @param urls URLs hacia los archivo XML o ZIP a leer
 * @return una lista de instancias FacturaReader
 *///from  w w  w .  j av a2 s. c o m
public static FacturaReader getFacturaElectronica(String url) throws Exception {
    FacturaReader facturaReader = null;

    if (url.endsWith(".xml")) {
        String xml = FacturaElectronicaURLReader.read(url);
        facturaReader = new FacturaReader(FacturaUtil.read(xml), xml, url);
    } else if (url.endsWith(".zip")) {
        URL url_ = new URL(url);
        InputStream is = url_.openStream();
        ZipInputStream zis = new ZipInputStream(is);
        try {

            ZipEntry entry = null;
            String tmp = null;
            ByteArrayOutputStream fout = null;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().toLowerCase().endsWith(".xml")) {
                    fout = new ByteArrayOutputStream();
                    for (int c = zis.read(); c != -1; c = zis.read()) {
                        fout.write(c);
                    }

                    tmp = new String(fout.toByteArray(), Charset.defaultCharset());
                    facturaReader = new FacturaReader(FacturaUtil.read(tmp), tmp, url);
                    fout.close();
                }
                zis.closeEntry();
            }
            zis.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(zis);
        }
    }

    return facturaReader;
}

From source file:com.microsoft.azurebatch.jenkins.utils.ZipHelper.java

private static void unzipFile(File zipFile, String outputFolderPath) throws FileNotFoundException, IOException {
    ZipInputStream zip = null;
    try {/*from   w w w  .j av a2s. c  om*/
        zip = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;

        while ((entry = zip.getNextEntry()) != null) {
            File entryFile = new File(outputFolderPath, entry.getName());
            if (entry.isDirectory()) {
                if (!entryFile.exists()) {
                    if (!entryFile.mkdirs()) {
                        throw new IOException(String.format("Failed to create folder %s %s", outputFolderPath,
                                entry.getName()));
                    }
                }
            } else {
                // Create parent folder if it's not exist
                File folder = entryFile.getParentFile();
                if (!folder.exists()) {
                    if (!folder.mkdirs()) {
                        throw new IOException(
                                String.format("Failed to create folder %s", folder.getAbsolutePath()));
                    }
                }

                // Create the target file
                if (!entryFile.createNewFile()) {
                    throw new IOException(
                            String.format("Failed to create entry file %s", entryFile.getAbsolutePath()));
                }

                // And rewrite data from stream
                OutputStream os = null;
                try {
                    os = new FileOutputStream(entryFile);
                    IOUtils.copy(zip, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:de.uni_hildesheim.sse.ant.versionReplacement.PluginVersionReplacer.java

/**
 * Unpacks an existing JAR/Zip archive./*ww w  . j  ava  2 s  .c  o m*/
 * 
 * @param zipFile The Archive file to unzip.
 * @param outputFolder The destination folder where the unzipped content shall be saved.
 * @see <a href="http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/">
 * http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/</a>
 */
private static void unZipIt(File zipFile, File outputFolder) {

    byte[] buffer = new byte[1024];

    try {

        // create output directory is not exists
        File folder = outputFolder;
        if (folder.exists()) {
            FileUtils.deleteDirectory(folder);
        }
        folder.mkdir();

        // get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder, fileName);

            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            if (!ze.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.frostwire.util.ZipUtils.java

private static void unzipEntries(File folder, ZipInputStream zis, int itemCount, long time,
        ZipListener listener) throws IOException, FileNotFoundException {
    ZipEntry ze = null;/*from   w w w  .j  ava2  s .  c om*/

    int item = 0;

    while ((ze = zis.getNextEntry()) != null) {
        item++;

        String fileName = ze.getName();
        File newFile = new File(folder, fileName);

        LOG.debug("unzip: " + newFile.getAbsoluteFile());

        if (ze.isDirectory()) {
            if (!newFile.mkdirs()) {
                break;
            }
            continue;
        }

        if (listener != null) {
            int progress = (item == itemCount) ? 100 : (int) (((double) (item * 100)) / (double) (itemCount));
            listener.onUnzipping(fileName, progress);
        }

        FileOutputStream fos = new FileOutputStream(newFile);

        try {
            int n;
            byte[] buffer = new byte[1024];
            while ((n = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, n);

                if (listener != null && listener.isCanceled()) { // not the best way
                    throw new IOException("Uncompress operation cancelled");
                }
            }
        } finally {
            fos.close();
            zis.closeEntry();
        }

        newFile.setLastModified(time);
    }
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public static TextFileLexicon deserialize(ZipInputStream zis) {
    TextFileLexicon memoryBase = null;/*from  w w w  .j a va  2s .  co  m*/
    try {
        ZipEntry zipEntry;
        if ((zipEntry = zis.getNextEntry()) != null) {
            LOG.debug("Scanning zip entry " + zipEntry.getName());

            ObjectInputStream in = new ObjectInputStream(zis);
            memoryBase = (TextFileLexicon) in.readObject();
            zis.closeEntry();
            in.close();
        } else {
            throw new RuntimeException("No zip entry in input stream");
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }

    return memoryBase;
}

From source file:Main.java

public static String unzip(String filename) throws IOException {
    BufferedOutputStream origin = null;
    String path = null;//www .  j ava 2 s. c om
    Integer BUFFER_SIZE = 20480;
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        String compressedFile = flockedFilesFolder.toString() + "/" + filename;
        System.out.println("compressed File name:" + compressedFile);
        //String uncompressedFile = flockedFilesFolder.toString()+"/"+"flockUnZip";
        File purgeFile = new File(compressedFile);

        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(compressedFile));
            BufferedInputStream bis = new BufferedInputStream(zin);
            try {
                ZipEntry ze = null;
                while ((ze = zin.getNextEntry()) != null) {
                    byte data[] = new byte[BUFFER_SIZE];
                    path = flockedFilesFolder.toString() + "/" + ze.getName();
                    System.out.println("path is:" + path);
                    if (ze.isDirectory()) {
                        File unzipFile = new File(path);
                        if (!unzipFile.isDirectory()) {
                            unzipFile.mkdirs();
                        }
                    } else {
                        FileOutputStream fout = new FileOutputStream(path, false);
                        origin = new BufferedOutputStream(fout, BUFFER_SIZE);
                        try {
                            /* for (int c = bis.read(data, 0, BUFFER_SIZE); c != -1; c = bis.read(data)) {
                            origin.write(c);
                             }
                             */
                            int count;
                            while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
                                origin.write(data, 0, count);
                            }
                            zin.closeEntry();
                        } finally {
                            origin.close();
                            fout.close();

                        }
                    }
                }
            } finally {
                bis.close();
                zin.close();
                purgeFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
    return null;
}