Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:org.scify.talkandplay.utils.Updater.java

private ArrayList<String> extractZip() {
    ArrayList<String> tempfilesThatWillReplaceTheExisting = new ArrayList<>();
    try {//w ww .  j  a va2 s.co m
        ZipInputStream zipIn = new ZipInputStream(
                new FileInputStream(properties.getTmpFolder() + File.separator + properties.getZipFile()));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = properties.getTmpFolder() + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                tempfilesThatWillReplaceTheExisting.add(filePath);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = new byte[1024];
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (IOException ex) {
        Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
    return tempfilesThatWillReplaceTheExisting;
}

From source file:org.infoscoop.service.GadgetResourceService.java

public void updateResources(String type, String moduleName, ZipInputStream zin) throws GadgetResourceException {
    gadgetDAO.deleteType(type);/*w  w w  .  j a  v  a2 s.com*/
    //gadgetIconDAO.deleteByType(type);

    boolean findModule = false;
    try {
        ZipEntry entry;
        while ((entry = getNextEntry(zin)) != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[5120];
                int reads = 0;
                while (!((reads = zin.read(buf)) < 0))
                    baos.write(buf, 0, reads);
                byte[] data = baos.toByteArray();

                String zipName = entry.getName();
                String path = "/" + zipName.substring(0, zipName.lastIndexOf("/") + 1);
                String name = zipName.substring(path.length() - 1);

                try {
                    if (path.length() > 1 && path.endsWith("/"))
                        path = path.substring(0, path.length() - 1);

                    if ("/".equals(path) && (moduleName + ".xml").equalsIgnoreCase(name)) {
                        findModule = true;
                        name = type + ".xml";

                        data = validateGadgetData(type, path, name, data);
                    }

                    insertResource(type, path, name, data);
                } catch (Exception ex) {
                    throw new GadgetResourceArchiveException(path, name,
                            "It is an entry of an invalid archive.  error at [" + path + "/" + name + "]"
                                    + ex.getMessage(),
                            "ams_gadgetResourceInvalidArchiveEntry", ex);
                }
            }

            zin.closeEntry();
        }
    } catch (GadgetResourceException ex) {
        throw ex;
    } catch (Exception ex) {
        log.error("", ex);

        throw new GadgetResourceException("It is an invalid archive.", "ams_gadgetResourceInvalidArchive");
    }

    if (!findModule)
        throw new GadgetResourceException(
                "Not found gadget module( /" + moduleName + ".xml" + " ) in an uploaded archive.",
                "ams_gadgetResourceNotFoundGadgetModule");
}

From source file:com.gatf.executor.report.ReportHandler.java

/**
  * @param zipFile//from  w  ww.  j  ava 2 s .  c om
  * @param directoryToExtractTo Provides file unzip functionality
  */
public static void unzipZipFile(InputStream zipFile, String directoryToExtractTo) {
    ZipInputStream in = new ZipInputStream(zipFile);
    try {
        File directory = new File(directoryToExtractTo);
        if (!directory.exists()) {
            directory.mkdirs();
            logger.info("Creating directory for Extraction...");
        }
        ZipEntry entry = in.getNextEntry();
        while (entry != null) {
            try {
                File file = new File(directory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileOutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.close();
                }
                in.closeEntry();
                entry = in.getNextEntry();
            } catch (Exception e) {
                logger.severe(ExceptionUtils.getStackTrace(e));
            }
        }
    } catch (IOException ioe) {
        logger.severe(ExceptionUtils.getStackTrace(ioe));
        return;
    }
}

From source file:com.bibisco.manager.ProjectManager.java

public static void unZipIt(String pStrZipFile) {

    mLog.debug("Start unZipIt(String)");

    try {//from w  w w.  j a va2 s .  c o  m
        // get temp directory path
        String lStrTempDirectory = ContextManager.getInstance().getTempDirectoryPath();

        // get the zip file content
        ZipInputStream lZipInputStream = new ZipInputStream(new FileInputStream(pStrZipFile));

        // get the zipped file list entry
        ZipEntry lZipEntry = lZipInputStream.getNextEntry();

        while (lZipEntry != null) {

            String lStrFileName = lZipEntry.getName();
            File lFileZipEntry = new File(lStrTempDirectory + File.separator + lStrFileName);

            // create all non exists folders
            new File(lFileZipEntry.getParent()).mkdirs();

            FileOutputStream lFileOutputStream = new FileOutputStream(lFileZipEntry);

            byte[] buffer = new byte[1024];
            int lIntLen;
            while ((lIntLen = lZipInputStream.read(buffer)) > 0) {
                lFileOutputStream.write(buffer, 0, lIntLen);
            }

            lFileOutputStream.close();
            lZipEntry = lZipInputStream.getNextEntry();
        }

        lZipInputStream.closeEntry();
        lZipInputStream.close();

    } catch (IOException e) {
        mLog.error(e);
        throw new BibiscoException(e, BibiscoException.IO_EXCEPTION);
    }

    mLog.debug("End unZipIt(String)");
}

From source file:org.wisdom.monitor.extensions.jcr.backup.ModeshapeJcrBackupExtension.java

public void unzip(File fileToUnzip, File folderToUnzipInto) {

    byte[] buffer = new byte[1024];

    try {//from w  w w  .  j a  v  a 2 s  .c  om
        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(fileToUnzip));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();
            File newFile = new File(folderToUnzipInto + File.separator + fileName);

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

            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:net.geoprism.data.importer.ShapefileImporter.java

@Request
public void run(InputStream iStream) throws InvocationTargetException {
    // create a buffer to improve copy performance later.
    byte[] buffer = new byte[2048];

    File directory = null;//ww w .  j av a  2 s. co m

    File first = null;

    try {
        directory = new File(FileUtils.getTempDirectory(),
                new Long(configuration.getGenerator().next()).toString());
        directory.mkdirs();

        ZipInputStream zstream = new ZipInputStream(iStream);

        ZipEntry entry;

        while ((entry = zstream.getNextEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (first == null && file.getName().endsWith("dbf")) {
                first = file;
            }

            FileOutputStream output = null;

            try {
                output = new FileOutputStream(file);

                int len = 0;

                while ((len = zstream.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
            } finally {
                if (output != null) {
                    output.close();
                }
            }
        }

        if (first != null) {
            this.createFeatures(first.toURI().toURL());
        } else {
            // TODO Change exception type
            throw new RuntimeException("Empty zip file");
        }
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    } finally {
        if (directory != null) {
            try {
                FileUtils.deleteDirectory(directory);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.pentaho.marketplace.domain.services.DiPluginService.java

/**
 * Unzips the plugin to the file system The passed MarkeyEntry has the URL of the zip file.
 * @throws KettleException/* w w w  .j a  v  a 2  s. co  m*/
 */
private static void unzipMarketEntry(String folderName, String packageUrl) throws KettleException {

    // Copy the file locally first
    //
    File tmpFile = null;
    InputStream inputStream = null;
    ZipInputStream zis = null;

    try {
        // using HttpUtil to handle http redirects
        InputStream urlInputStream = HttpUtil.getURLInputStream(packageUrl);
        if (urlInputStream == null) {
            throw new KettleException("Unable get file from " + packageUrl);
        }
        tmpFile = File.createTempFile("plugin", ".zip");
        org.apache.commons.io.FileUtils.copyInputStreamToFile(urlInputStream, tmpFile);

        // Read the package, extract in folder
        //
        inputStream = new FileInputStream(tmpFile);
        zis = new ZipInputStream(inputStream);
        ZipEntry zipEntry = null;
        try {
            zipEntry = zis.getNextEntry();
        } catch (IOException ioe) {
            throw new KettleException(ioe);
        }
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        FileOutputStream fos = null;

        while (zipEntry != null) {
            try {
                File file = new File(folderName + File.separator + zipEntry.getName());

                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                } else {
                    file.getParentFile().mkdirs();

                    fos = new FileOutputStream(file);
                    while ((bytesRead = zis.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }

                zipEntry = zis.getNextEntry();
            } catch (FileNotFoundException fnfe) {
                throw new KettleException(fnfe);
            } catch (IOException ioe) {
                throw new KettleException(ioe);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // Ignore.
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new KettleException("Unable to unzip file " + packageUrl, e);
    } finally {
        if (zis != null) {
            tmpFile.delete();
            try {
                zis.close();
            } catch (Exception e) {
                throw new KettleException("Unable to close zip file stream (corrupt file?) of file " + tmpFile,
                        e);
            }
        }
    }

}

From source file:org.jwebsocket.util.Tools.java

/**
 * Unzip a ZIP file into an output directory
 *
 * @see http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/
 *
 * @param aZipFile input zip file/*from   ww  w  .  j  av a 2  s  .  co m*/
 * @param aOutputDirectory
 * @throws IOException
 */
public static void unzip(File aZipFile, File aOutputDirectory) throws IOException {

    byte[] lBuffer = new byte[1024];

    //create output directory is not exists
    if (!aOutputDirectory.exists()) {
        aOutputDirectory.mkdir();
    }

    //get the zip file content
    ZipInputStream lZIS = new ZipInputStream(new FileInputStream(aZipFile));
    //get the zipped file list entry
    ZipEntry lZE = lZIS.getNextEntry();

    while (lZE != null) {
        String lFileName = lZE.getName();
        File lNewFile = new File(aOutputDirectory.getCanonicalPath() + File.separator + lFileName);

        if (lZE.isDirectory()) {
            lNewFile.mkdir();
        } else {
            FileOutputStream lFOS = new FileOutputStream(lNewFile);
            int lLength;
            while ((lLength = lZIS.read(lBuffer)) > 0) {
                lFOS.write(lBuffer, 0, lLength);
            }

            lFOS.close();
        }
        lZE = lZIS.getNextEntry();
    }

    lZIS.closeEntry();
    lZIS.close();
}

From source file:org.tinymediamanager.core.tvshow.tasks.TvShowSubtitleDownloadTask.java

@Override
protected void doInBackground() {
    // let the DownloadTask handle the whole download
    super.doInBackground();

    MediaFile mf = new MediaFile(file);

    if (mf.getType() != MediaFileType.SUBTITLE) {
        String basename = FilenameUtils.getBaseName(file.getFileName().toString());

        // try to decompress
        try {//  www .  j  av  a 2 s .  c o m
            byte[] buffer = new byte[1024];

            ZipInputStream is = new ZipInputStream(new FileInputStream(file.toFile()));

            // get the zipped file list entry
            ZipEntry ze = is.getNextEntry();

            while (ze != null) {
                String zipEntryFilename = ze.getName();
                String extension = FilenameUtils.getExtension(zipEntryFilename);

                // check is that is a valid file type
                if (!Globals.settings.getSubtitleFileType().contains("." + extension)) {
                    ze = is.getNextEntry();
                    continue;
                }

                File destination = new File(file.getParent().toFile(), basename + "." + extension);
                FileOutputStream os = new FileOutputStream(destination);

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

                os.close();
                mf = new MediaFile(destination.toPath());

                // only take the first subtitle
                break;
            }
            is.closeEntry();
            is.close();

            Utils.deleteFileSafely(file);
        } catch (Exception e) {
        }
    }

    mf.gatherMediaInformation();
    episode.removeFromMediaFiles(mf); // remove old (possibly same) file
    episode.addToMediaFiles(mf); // add file, but maybe with other MI values
    episode.saveToDb();
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private boolean unpackZip(File output_dir, File zipname) {
    InputStream is;/*  w ww. j a v a  2  s .co m*/
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(zipname);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

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

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(output_dir, filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(new File(output_dir, filename));

            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}