Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

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

private boolean unpackZip(File output_dir, File zipname) {
    InputStream is;/* ww  w. j a  v  a 2 s .c om*/
    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;
}

From source file:org.theospi.portfolio.guidance.impl.GuidanceManagerImpl.java

/**
 * This function is up to spec but incomplete.  The guidance security qualifier
 * needs to be set on these objects so they can be retrieved.
 * //from ww w.j a  v  a  2 s  .co  m
 * @param parent the parent resource folder where attachments go
 * @param siteId the site which will recieve the imported "stuff"
 * @param in  The Input stream representing the output stream of the export
 * @return Map contains a map with keys being of type String as old Ids and the 
 * values as being the Guidance object
 */
public Map importGuidanceList(ContentCollection parent, String siteId, InputStream in) throws IOException {
    Map guidanceMap = new Hashtable();
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry currentEntry = zis.getNextEntry();

    Map attachmentMap = new Hashtable();

    while (currentEntry != null) {
        if (!currentEntry.isDirectory()) {
            if (currentEntry.getName().startsWith("guidance-")) {
                importGuidance(siteId, zis, guidanceMap);
            } else if (currentEntry.getName().startsWith("attachments/")) {
                importAttachmentRef(parent, currentEntry, siteId, zis, attachmentMap);
            }
        }

        zis.closeEntry();
        currentEntry = zis.getNextEntry();
    }

    postPocessAttachments(guidanceMap.values(), attachmentMap);

    for (Iterator i = guidanceMap.values().iterator(); i.hasNext();) {
        Guidance guidance = (Guidance) i.next();
        saveGuidance(guidance);
    }

    return guidanceMap;
}

From source file:es.eucm.mokap.backend.controller.insert.MokapInsertController.java

/**
 * Processes a temp file stored in Cloud Storage: -It analyzes its contents
 * -Processes the descriptor.json file and stores the entity in Datastore
 * -Finally it stores the thumbnails and contents.zip in Cloud Storage
 * //from  w w  w  .j a  v a 2s .c  om
 * @param tempFileName
 *            name of the temp file we are going to process
 * @return The Datastore Key id for the entity we just created (entityRef in
 *         RepoElement)
 * @throws IOException
 *             If the file is not accessible or Cloud Storage is not
 *             available ServerError If a problem is found with the internal
 *             structure of the file
 */
private long processUploadedTempFile(String tempFileName) throws IOException, ServerError {
    long assignedKeyId;
    // Read the cloud storage file
    byte[] content = null;
    String descriptor = "";
    Map<String, byte[]> tns = new HashMap<String, byte[]>();
    InputStream is = st.readFile(tempFileName);
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        String filename = entry.getName();
        if (UploadZipStructure.isContentsFile(filename)) {
            content = IOUtils.toByteArray(zis);
        } else if (UploadZipStructure.isDescriptorFile(filename)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8"));
            String str;
            while ((str = br.readLine()) != null) {
                descriptor += str;
            }
        } else if (entry.isDirectory()) {
            continue;
        }
        // Should be a thumbnail
        else if (UploadZipStructure.checkThumbnailImage(filename)) {
            byte[] img = IOUtils.toByteArray(zis);
            tns.put(filename, img);
        }
        zis.closeEntry();
    }

    try {
        if (descriptor != null && !descriptor.equals("") && content != null) {
            // Analizar json
            Map<String, Object> entMap = Utils.jsonToMap(descriptor);
            // Parse the map into an entity
            Entity ent = new Entity("Resource");
            for (String key : entMap.keySet()) {
                ent.setProperty(key, entMap.get(key));
            }
            // Store the entity (GDS) and get the Id
            Key k = db.storeEntity(ent);
            assignedKeyId = k.getId();

            // Store the contents file with the Id in the name
            ByteArrayInputStream bis = new ByteArrayInputStream(content);
            st.storeFile(bis, assignedKeyId + UploadZipStructure.ZIP_EXTENSION);

            // Store the thumbnails in a folder with the id as the name
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.storeFile(imgs, assignedKeyId + "/" + key);
            }
            // Create the Search Index Document
            db.addToSearchIndex(ent, k);

            // Everything went ok, so we delete the temp file
            st.deleteFile(tempFileName);
        } else {
            assignedKeyId = 0;
            if (descriptor == null || descriptor.equals("")) {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_DESCRIPTOR);
            } else {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_CONTENT);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        assignedKeyId = 0;
        // Force rollback if anything failed
        try {
            st.deleteFile(tempFileName);
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.deleteFile(assignedKeyId + "/" + key);
            }
            db.deleteEntity(assignedKeyId);
        } catch (Exception ex) {
        }
    }
    return assignedKeyId;
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

/**
 * Decompresses the file in it's current location
 *///from   w w  w .jav  a  2  s.c  om
public void unzip() throws JahiaException {

    try {

        File f = new File(m_FilePath);

        //JahiaConsole.println(CLASS_NAME + ".upzip"," Start Decompressing " + f.getName() );

        String parentPath = f.getParent() + File.separator;
        String path = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        try {

            while ((ze = zis.getNextEntry()) != null) {
                zeName = ze.getName();
                path = parentPath + genPathFile(zeName);
                File fo = new File(path);

                if (ze.isDirectory()) {
                    fo.mkdirs();
                } else {
                    copyStream(zis, new FileOutputStream(fo));
                }
                zis.closeEntry();
            }
        } finally {

            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

        //JahiaConsole.println(CLASS_NAME+".unzip"," Decompressing " + f.getName() + " done ! ");

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException("JahiaArchiveFileHandler", "faile processing unzip",
                JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, ioe);

    }

}

From source file:com.theaetetuslabs.apkmakertester.ApkMakerService.java

private boolean unpackZip(String pathToZip, String destPath) {
    new File(destPath).mkdirs();
    InputStream is;//from w ww. j  av  a 2 s  . c  o m
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(pathToZip);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            // zapis do souboru
            filename = ze.getName();

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

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

            // cteni zipu a zapis
            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;
}

From source file:org.arquillian.warp.ftest.installation.ContainerInstaller.java

private void unzip(InputStream inputStream, File destination, boolean overwrite) {
    try {//from  w w w. ja  v  a  2s  . com
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(inputStream);

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(destination, zipentry.getName());
            if (zipentry.isDirectory()) {
                newFile.mkdirs();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.exists() && overwrite) {
                log.info("Overwriting " + newFile);
                newFile.delete();
            }

            fileoutputstream = new FileOutputStream(newFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

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

        }

        zipinputstream.close();
    } catch (Exception e) {
        throw new IllegalStateException("Can't unzip input stream", e);
    }
}

From source file:org.peercast.core.PeerCastService.java

private void assetInstall() throws IOException {
    File dataDir = getFilesDir();

    ZipInputStream zipIs = new ZipInputStream(getAssets().open("peca.zip"));
    try {/*from  w w  w  . j av a2  s  .c  om*/
        ZipEntry ze;
        while ((ze = zipIs.getNextEntry()) != null) {
            File file = new File(dataDir, ze.getName());
            if (file.exists())
                continue;

            if (ze.isDirectory()) {
                file.mkdirs();
                continue;
            }
            file.getParentFile().mkdirs();
            Log.d(TAG, "Install resource -> " + file.getAbsolutePath());
            FileOutputStream fout = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = zipIs.read(buffer)) > 0) {
                fout.write(buffer, 0, length);
            }
            zipIs.closeEntry();
            fout.close();
        }
    } finally {
        zipIs.close();
    }
}

From source file:org.ado.minesync.commons.ZipArchiver.java

public void unpackZip(FileInputStream inputStream, File outputDir) throws IOException {
    notNull(inputStream, "inputStream cannot be null");
    notNull(outputDir, "outputDir cannot be null");

    ALog.d(TAG, "unzip stream to [" + outputDir.getAbsolutePath() + "]");
    ZipInputStream zipInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {//from   w  ww. ja v  a 2s  .c om
        String filename;
        zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;
        byte[] buffer = new byte[BUFFER];
        int count;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            filename = zipEntry.getName();
            ALog.v(TAG, "creating file [" + filename + "].");

            if (isZipEntryInDirectory(zipEntry)) {
                File directory = new File(outputDir, getDirectoryName(filename));
                forceMkdir(directory);
            }

            File file = new File(outputDir, filename);
            fileOutputStream = new FileOutputStream(file);
            while ((count = zipInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, count);
            }
            zipInputStream.closeEntry();

        }

    } finally {
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(inputStream);
    }
}

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 .  ja  v  a 2  s .c om
 * @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:com.bibisco.manager.ProjectManager.java

public static void unZipIt(String pStrZipFile) {

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

    try {/*  w w w.j a v  a 2s.  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)");
}