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:com.wakatime.eclipse.plugin.Dependencies.java

private void unzip(String zipFile, File outputDir) throws IOException {
    if (!outputDir.exists())
        outputDir.mkdirs();/*from  w w  w  . j a  v  a  2 s .  co  m*/

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            // WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath());
            newFile.mkdirs();
        } else {
            // WakaTime.log("Extracting File: "+newFile.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

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

From source file:com.wso2mobile.mam.packageExtractor.ZipFileReading.java

public String readiOSManifestFile(String filePath, String name) {
    String plist = "";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {/* w  ww  . j  av  a2 s  . c om*/
        File file = new File(filePath);
        ZipInputStream stream = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                if (entry.getName().equals("Payload/" + name + ".app/Info.plist")) {
                    InputStream is = stream;

                    int nRead;
                    byte[] data = new byte[16384];

                    while ((nRead = is.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, nRead);
                    }

                    buffer.flush();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }
        NSDictionary rootDict = (NSDictionary) BinaryPropertyListParser.parse(buffer.toByteArray());
        JSONObject obj = new JSONObject();
        obj.put("version", rootDict.objectForKey("CFBundleVersion").toString());
        obj.put("name", rootDict.objectForKey("CFBundleName").toString());
        obj.put("package", rootDict.objectForKey("CFBundleIdentifier").toString());
        plist = obj.toJSONString();
    } catch (Exception e) {
        plist = "Exception occured " + e;
        e.printStackTrace();
    }
    return plist;
}

From source file:edu.ku.brc.helpers.ZipFileHelper.java

/**
 * Unzips a a zip file cntaining just one file.
 * @param zipFile the backup file//from w w w . jav a  2 s.c om
 * @return the file of the new uncompressed back up file.
 */
public File unzipToSingleFile(final File zipFile) {
    final int bufSize = 102400;

    File outFile = null;
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        if (entry == null) {
            return null;
        }
        if (zin.available() == 0) {
            return null;
        }
        outFile = File.createTempFile("zip_", "sql");
        FileOutputStream fos = new FileOutputStream(outFile);

        byte[] bytes = new byte[bufSize]; // 10K
        int bytesRead = zin.read(bytes, 0, bufSize);
        while (bytesRead > 0) {
            fos.write(bytes, 0, bytesRead);
            bytesRead = zin.read(bytes, 0, 100);
        }

    } catch (ZipException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ZipFileHelper.class, ex);
        return null; //I think this means it is not a zip file.

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ZipFileHelper.class, ex);
        return null;
    }
    return outFile;
}

From source file:com.ibm.liberty.starter.ProjectZipConstructor.java

public void initializeMap() throws IOException {
    System.out.println("Entering method ProjectZipConstructor.initializeMap()");
    InputStream skeletonIS = this.getClass().getClassLoader().getResourceAsStream(SKELETON_JAR_FILENAME);
    ZipInputStream zis = new ZipInputStream(skeletonIS);
    ZipEntry ze;//from  w  w w .j  a va 2s  .co  m
    while ((ze = zis.getNextEntry()) != null) {
        String path = ze.getName();
        int length = 0;
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((length = zis.read(bytes)) != -1) {
            baos.write(bytes, 0, length);
        }
        putFileInMap(path, baos.toByteArray());
    }
    zis.close();
}

From source file:be.fedict.eid.dss.document.zip.ZIPSignatureService.java

@Override
protected Document getEnvelopingDocument() throws ParserConfigurationException, IOException, SAXException {
    FileInputStream fileInputStream = new FileInputStream(this.tmpFile);
    ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
    ZipEntry zipEntry;/*  w  ww  .j a v a 2s. c  om*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
            return documentSignaturesDocument;
        }
    }
    Document document = ODFUtil.getNewDocument();
    Element rootElement = document.createElementNS(ODFUtil.SIGNATURE_NS, ODFUtil.SIGNATURE_ELEMENT);
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ODFUtil.SIGNATURE_NS);
    document.appendChild(rootElement);
    return document;
}

From source file:edu.ku.brc.helpers.ZipFileHelper.java

/**
 * @param zipFile/*from  w ww .  j  a  v  a  2  s  . c  om*/
 * @return
 * @throws ZipException
 * @throws IOException
 */
public List<File> unzipToFiles(final File zipFile) throws ZipException, IOException {
    Vector<File> files = new Vector<File>();

    final int bufSize = 65535;

    File dir = UIRegistry.getAppDataSubDir(Long.toString(System.currentTimeMillis()) + "_zip", true);
    dirsToRemoveList.add(dir);

    File outFile = null;
    FileOutputStream fos = null;
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            if (zin.available() > 0) {
                outFile = new File(dir.getCanonicalPath() + File.separator + entry.getName());
                fos = new FileOutputStream(outFile);

                byte[] bytes = new byte[bufSize]; // 64k
                int bytesRead = zin.read(bytes, 0, bufSize);
                while (bytesRead > 0) {
                    fos.write(bytes, 0, bytesRead);
                    bytesRead = zin.read(bytes, 0, bufSize);
                }

                files.insertElementAt(outFile.getCanonicalFile(), 0);
            }
            entry = zin.getNextEntry();
        }

    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return files;
}

From source file:com.joliciel.talismane.machineLearning.ModelFactory.java

public MachineLearningModel getMachineLearningModel(ZipInputStream zis) {
    try {/*from   w w w .ja va2s . co  m*/
        MachineLearningModel machineLearningModel = null;
        ZipEntry ze = zis.getNextEntry();
        if (!ze.getName().equals("algorithm.txt")) {
            throw new JolicielException("Expected algorithm.txt as first entry in zip. Was: " + ze.getName());
        }

        // note: assuming the model type will always be the first entry
        Scanner typeScanner = new Scanner(zis, "UTF-8");
        MachineLearningAlgorithm algorithm = MachineLearningAlgorithm.MaxEnt;
        if (typeScanner.hasNextLine()) {
            String algorithmString = typeScanner.nextLine();
            try {
                algorithm = MachineLearningAlgorithm.valueOf(algorithmString);
            } catch (IllegalArgumentException iae) {
                LogUtils.logError(LOG, iae);
                throw new JolicielException("Unknown algorithm: " + algorithmString);
            }
        } else {
            throw new JolicielException("Cannot find algorithm in zip file");
        }
        switch (algorithm) {
        case MaxEnt:
            machineLearningModel = maxentService.getMaxentModel();
            break;
        case LinearSVM:
            machineLearningModel = linearSVMService.getLinearSVMModel();
            break;
        case Perceptron:
            machineLearningModel = perceptronService.getPerceptronModel();
            break;
        case PerceptronRanking:
            machineLearningModel = perceptronService.getPerceptronRankingModel();
            break;
        case OpenNLPPerceptron:
            machineLearningModel = maxentService.getPerceptronModel();
            break;
        default:
            throw new JolicielException("Machine learning algorithm not yet supported: " + algorithm);
        }

        while ((ze = zis.getNextEntry()) != null) {
            LOG.debug(ze.getName());
            machineLearningModel.loadZipEntry(zis, ze);
        } // next zip entry

        machineLearningModel.onLoadComplete();

        return machineLearningModel;
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    } finally {
        try {
            zis.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
        }
    }
}

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

/**
 * /*w ww.  j  ava  2 s.c om*/
 * @param path
 * @param zip
 * @param out
 * @throws IOException
 */
protected void extractEntry(String path, ZipInputStream zip, OutputStream out) throws IOException {

    // Use as regex for more flexibility...
    Pattern p = Pattern.compile(path);

    ZipEntry entry = null;
    while ((entry = zip.getNextEntry()) != null) {
        Matcher m = p.matcher(entry.getName());
        if (m.matches()) {
            IOUtils.copy(zip, out);
            zip.closeEntry();
            break;
        }
    }
}

From source file:com.googlecode.jsfFlex.shared.tasks.sdk.UnzipTask.java

protected void performTask() {

    BufferedOutputStream bufferOutputStream = null;
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(_file));
    ZipEntry entry;/*from  ww w  . j  a  v a2  s. c  om*/

    try {

        while ((entry = zipInputStream.getNextEntry()) != null) {

            ensureDirectoryExists(entry.getName(), entry.isDirectory());

            bufferOutputStream = new BufferedOutputStream(new FileOutputStream(_dest + entry.getName()),
                    BUFFER_SIZE);
            int currRead = 0;
            byte[] dataRead = new byte[BUFFER_SIZE];

            while ((currRead = zipInputStream.read(dataRead, 0, BUFFER_SIZE)) != -1) {
                bufferOutputStream.write(dataRead, 0, currRead);
            }
            bufferOutputStream.flush();
            bufferOutputStream.close();
        }

        _log.debug("UnzipTask performTask has been completed with " + toString());
    } catch (IOException ioExcept) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Error in Unzip's performTask with following fields \n");
        errorMessage.append(toString());
        throw new ComponentBuildException(errorMessage.toString(), ioExcept);
    } finally {
        try {
            zipInputStream.close();
            if (bufferOutputStream != null) {
                bufferOutputStream.close();
            }
        } catch (IOException innerIOExcept) {
            _log.info("Error while closing the streams within UnzipTask's finally block");
        }
    }

}

From source file:com.seer.datacruncher.streams.ZipStreamTest.java

@Test
public void testZipStream() {
    String fileName = properties.getProperty("zip_test_stream_file_name");
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(stream_file_path + fileName);
    byte[] arr = null;
    try {/* w ww  .j a  va 2 s  .  com*/
        arr = IOUtils.toByteArray(in);
    } catch (IOException e) {
        assertTrue("IOException while Zip test file reading", false);
    }

    ZipInputStream inStream = null;
    try {
        inStream = new ZipInputStream(new ByteArrayInputStream(arr));
        ZipEntry entry;
        while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                DatastreamsInput datastreamsInput = new DatastreamsInput();
                datastreamsInput.setUploadedFileName(entry.getName());
                byte[] byteInput = IOUtils.toByteArray(inStream);
                String res = datastreamsInput.datastreamsInput(null, (Long) schemaEntity.getIdSchema(),
                        byteInput, true);
                assertTrue("Zip file validation failed", Boolean.parseBoolean(res));
            }
            inStream.closeEntry();
        }
    } catch (IOException ex) {
        assertTrue("Error occured during fetch records from ZIP file.", false);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
    }
}