List of usage examples for java.util.zip ZipFile size
public int size()
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean unzipSync(File targetFile, String outputDirectory, ProgressEvent progress, CallbackContext callbackContext) { Log.d(LOG_TAG, "unzipSync called"); Log.d(LOG_TAG, "zip = " + targetFile.getAbsolutePath()); InputStream inputStream = null; ZipFile zip = null; boolean anyEntries = false; try {/*from w w w . j a v a 2s.co m*/ synchronized (progress) { if (progress.isAborted()) { return false; } } zip = new ZipFile(targetFile); // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile:// // Accept a path or a URI for the source zip. Uri zipUri = getUriForArg(targetFile.getAbsolutePath()); Uri outputUri = getUriForArg(outputDirectory); CordovaResourceApi resourceApi = webView.getResourceApi(); File tempFile = resourceApi.mapUriToFile(zipUri); if (tempFile == null || !tempFile.exists()) { sendErrorMessage("Zip file does not exist", UNZIP_ERROR, callbackContext); } File outputDir = resourceApi.mapUriToFile(outputUri); outputDirectory = outputDir.getAbsolutePath(); outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator; if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) { sendErrorMessage("Could not create output directory", UNZIP_ERROR, callbackContext); } OpenForReadResult zipFile = resourceApi.openForRead(zipUri); progress.setStatus(STATUS_EXTRACTING); progress.setLoaded(0); progress.setTotal(zip.size()); Log.d(LOG_TAG, "zip file len = " + zip.size()); inputStream = new BufferedInputStream(zipFile.inputStream); inputStream.mark(10); int magic = readInt(inputStream); if (magic != 875721283) { // CRX identifier inputStream.reset(); } else { // CRX files contain a header. This header consists of: // * 4 bytes of magic number // * 4 bytes of CRX format version, // * 4 bytes of public key length // * 4 bytes of signature length // * the public key // * the signature // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream. readInt(inputStream); // version == 2. int pubkeyLength = readInt(inputStream); int signatureLength = readInt(inputStream); inputStream.skip(pubkeyLength + signatureLength); } // The inputstream is now pointing at the start of the actual zip file content. ZipInputStream zis = new ZipInputStream(inputStream); inputStream = zis; ZipEntry ze; byte[] buffer = new byte[32 * 1024]; while ((ze = zis.getNextEntry()) != null) { synchronized (progress) { if (progress.isAborted()) { return false; } } anyEntries = true; String compressedName = ze.getName(); if (ze.getSize() > getFreeSpace()) { return false; } if (ze.isDirectory()) { File dir = new File(outputDirectory + compressedName); dir.mkdirs(); } else { File file = new File(outputDirectory + compressedName); file.getParentFile().mkdirs(); if (file.exists() || file.createNewFile()) { Log.w(LOG_TAG, "extracting: " + file.getPath()); FileOutputStream fout = new FileOutputStream(file); int count; while ((count = zis.read(buffer)) != -1) { fout.write(buffer, 0, count); } fout.close(); } } progress.addLoaded(1); updateProgress(callbackContext, progress); zis.closeEntry(); } } catch (Exception e) { String errorMessage = "An error occurred while unzipping."; sendErrorMessage(errorMessage, UNZIP_ERROR, callbackContext); Log.e(LOG_TAG, errorMessage, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (zip != null) { try { zip.close(); } catch (IOException e) { } } } if (anyEntries) return true; else return false; }
From source file:com.amalto.workbench.utils.Util.java
/** * DOC hbhong Comment method "unZipFile". same with unZipFile(String zipfile, String unzipdir) method except having * a progressMonitor//from w ww . j a v a 2 s.com * * @param zipfile * @param unzipdir * @param totalProgress * @param monitor * @throws IOException * @throws Exception */ public static void unZipFile(String zipfile, String unzipdir, int totalProgress, IProgressMonitor monitor) throws IOException { monitor.setTaskName(Messages.Util_50); File unzipF = new File(unzipdir); if (!unzipF.exists()) { unzipF.mkdirs(); } ZipFile zfile = null; try { zfile = new ZipFile(zipfile); int total = zfile.size(); // System.out.println("zip's entry size:"+total); int interval, step; if (totalProgress / total > 0) { interval = 1; step = Math.round(totalProgress / total); } else { step = 1; interval = Math.round(total / totalProgress + 0.5f); } Enumeration zList = zfile.entries(); ZipEntry ze = null; byte[] buf = new byte[1024]; int tmp = 1; while (zList.hasMoreElements()) { ze = (ZipEntry) zList.nextElement(); monitor.subTask(ze.getName()); if (ze.isDirectory()) { File f = new File(unzipdir + ze.getName()); f.mkdirs(); continue; } unzipdir = unzipdir.replace('\\', '/'); if (!unzipdir.endsWith("/")) { //$NON-NLS-1$ unzipdir = unzipdir + "/"; //$NON-NLS-1$ } String filename = unzipdir + ze.getName(); File zeF = new File(filename); if (!zeF.getParentFile().exists()) { zeF.getParentFile().mkdirs(); } OutputStream os = null; InputStream is = null; try { os = new BufferedOutputStream(new FileOutputStream(zeF)); is = new BufferedInputStream(zfile.getInputStream(ze)); int readLen = 0; while ((readLen = is.read(buf, 0, 1024)) != -1) { os.write(buf, 0, readLen); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (is != null) { is.close(); } } catch (Exception e) { } try { if (os != null) { os.close(); } } catch (Exception e) { } } // update monitor if (interval == 1) { monitor.worked(step); } else { if (tmp >= interval) { monitor.worked(step); tmp = 1; } else { tmp++; } } } } catch (IOException e) { log.error(e.getMessage(), e); throw e; } finally { if (zfile != null) { try { zfile.close(); } catch (IOException e) { } } } }
From source file:com.pari.pcb.zip.ZIPProcessor.java
public void process(boolean blocking) { tmpRoot = new File("TEMP" + File.separator + "ZIP_TMP_" + System.nanoTime()); tmpRoot.mkdirs();/*ww w . j a v a2s . c om*/ long start = System.currentTimeMillis(); if (!zipFile.exists()) { errMsg = "File " + fileName + " does not exist"; setCompleted(); return; } if (!zipFile.canRead()) { errMsg = "Unable to read the contents of the file " + fileName; setCompleted(); return; } try { ZipFile inZip = new ZipFile(zipFile); numEntries = inZip.size(); Enumeration<? extends ZipEntry> entryEnumeration = inZip.entries(); if (numEntries == 0) { errMsg = "Empty ZIP file."; setCompleted(); return; } while (entryEnumeration.hasMoreElements()) { ZipEntry entry = entryEnumeration.nextElement(); currentEntryName = entry.getName(); if (entry.isDirectory()) { if (numEntries > 1) { numEntries--; } continue; } currentEntryIdx++; if (currentEntryIdx % 100 == 0) { System.gc(); NCCMObserver.getInstance().logMemoryUsage( "After handling " + currentEntryIdx + " files in Zip Processor, Memory Usage"); } InputStream ipStream = inZip.getInputStream(entry); String fileName = entry.getName(); System.err.println("Processing file: " + fileName); String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(ipStream)); line = br.readLine(); CharsetDetector detector = new CharsetDetector(); if (entry.getSize() == 0) { logger.error("No Contents found in the file"); continue; } else { detector.setText(line.getBytes()); charset = Charset.forName(detector.detect().getName()); } } catch (Exception ex) { logger.error("Error while getting the charset encoding of the file"); } finally { try { ipStream.close(); } catch (Exception e) { logger.error("Exception while closing the stream"); } } ipStream = inZip.getInputStream(entry); processZipEntry(ipStream, fileName, entry, inZip); if (progressIf != null) { progressIf.updateProgress(currentEntryName, currentEntryIdx, numEntries); } if (fileResultMap.get(fileName) == null) { ZIPFileResult fr = new ZIPFileResult(fileName); fr.fileType = ZIPFileType.UNKNOWN; fr.msg = "Unable to process the file."; fileResultMap.put(fileName, fr); } try { ipStream.close(); } catch (Exception ex) { logger.warn("Unable to close the inputstream for entry " + entry.getName(), ex); ex.printStackTrace(); } if (isCancelled) { break; } if (!blocking) { Thread.sleep(100 /* msec */); } if (isCancelled) { break; } } if (!isCancelled) { processCatOsVersionFiles(inZip); processFileResult(); } inZip.close(); } catch (ZipException e) { errMsg = "File is not a valid Zip file"; logger.error("Exception while processing ZipFile: " + fileName, e); } catch (IOException e) { errMsg = "Unable to parse Zip file "; logger.error("IOException while processing ZipFile: " + fileName, e); } catch (InterruptedException e) { errMsg = "Zip processing Interrupted internally."; logger.error("Interrupted while processing ZipFile: " + fileName, e); } catch (Exception e) { errMsg = "Exception while processing zip file."; logger.error("Exception while processing ZipFile: " + fileName, e); } logger.debug("Done with : " + numEntries + " in " + (System.currentTimeMillis() - start) + " msecs"); String[] devNames = getDeviceNames(); if (devNames == null || devNames.length == 0) { addWarning("No valid devices found in the specified Zip file."); } setCompleted(); return; }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String Unzip(String zipFileName, String dstDirectory) { String sRet = ""; String fixedZipFileName = fixFileName(zipFileName); String fixedDstDirectory = fixFileName(dstDirectory); String dstFileName = ""; int nNumExtracted = 0; boolean bRet = false; try {/*from w w w . j av a 2 s.c o m*/ final int BUFFER = 2048; BufferedOutputStream dest = null; ZipFile zipFile = new ZipFile(fixedZipFileName); int nNumEntries = zipFile.size(); zipFile.close(); FileInputStream fis = new FileInputStream(fixedZipFileName); CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32()); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum)); ZipEntry entry; byte[] data = new byte[BUFFER]; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; if (fixedDstDirectory.length() > 0) dstFileName = fixedDstDirectory + entry.getName(); else dstFileName = entry.getName(); String tmpDir = dstFileName.substring(0, dstFileName.lastIndexOf('/')); File tmpFile = new File(tmpDir); if (!tmpFile.exists()) { bRet = tmpFile.mkdirs(); } else bRet = true; if (bRet) { // if we aren't just creating a directory if (dstFileName.lastIndexOf('/') != (dstFileName.length() - 1)) { // write out the file FileOutputStream fos = new FileOutputStream(dstFileName); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); dest = null; fos.close(); fos = null; } nNumExtracted++; } else sRet += " - failed" + lineSep; } data = null; zis.close(); System.out.println("Checksum: " + checksum.getChecksum().getValue()); sRet += "Checksum: " + checksum.getChecksum().getValue(); sRet += lineSep + nNumExtracted + " of " + nNumEntries + " successfully extracted"; } catch (Exception e) { e.printStackTrace(); } return (sRet); }