List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getInputStream
public InputStream getInputStream(ZipArchiveEntry ze) throws IOException, ZipException
From source file:com.nit.libanki.Utils.java
public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries, HashMap<String, String> zipEntryToFilenameMap) { byte[] buf = new byte[FILE_COPY_BUFFER_SIZE]; File dir = new File(targetDirectory); if (!dir.exists() && !dir.mkdirs()) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory); return false; }/*from ww w. jav a 2 s.c om*/ if (zipEntryToFilenameMap == null) { zipEntryToFilenameMap = new HashMap<String, String>(); } BufferedInputStream zis = null; BufferedOutputStream bos = null; try { for (String requestedEntry : zipEntries) { ZipArchiveEntry ze = zipFile.getEntry(requestedEntry); if (ze != null) { String name = ze.getName(); if (zipEntryToFilenameMap.containsKey(name)) { name = zipEntryToFilenameMap.get(name); } File destFile = new File(dir, name); File parentDir = destFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { return false; } if (!ze.isDirectory()) { // Log.i(AnkiDroidApp.TAG, "uncompress " + name); zis = new BufferedInputStream(zipFile.getInputStream(ze)); bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE); int n; while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) { bos.write(buf, 0, n); } bos.flush(); bos.close(); zis.close(); } } } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e); return false; } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e); } try { if (zis != null) { zis.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e); } } return true; }
From source file:adams.core.io.ZipUtils.java
/** * Unzips the specified file from a ZIP file. * * @param input the ZIP file to unzip//w ww . ja va 2 s . c o m * @param archiveFile the file from the archive to extract * @param output the name of the output file * @param createDirs whether to create the directory structure represented * by output file * @param bufferSize the buffer size to use * @param errors for storing potential errors * @return whether file was successfully extracted */ public static boolean decompress(File input, String archiveFile, File output, boolean createDirs, int bufferSize, StringBuilder errors) { boolean result; ZipFile zipfile; Enumeration<ZipArchiveEntry> enm; ZipArchiveEntry entry; File outFile; String outName; byte[] buffer; BufferedInputStream in; BufferedOutputStream out; FileOutputStream fos; int len; String error; long read; result = false; zipfile = null; try { // unzip archive buffer = new byte[bufferSize]; zipfile = new ZipFile(input.getAbsoluteFile()); enm = zipfile.getEntries(); while (enm.hasMoreElements()) { entry = enm.nextElement(); if (entry.isDirectory()) continue; if (!entry.getName().equals(archiveFile)) continue; in = null; out = null; fos = null; outName = null; try { // output name outName = output.getAbsolutePath(); // create directory, if necessary outFile = new File(outName).getParentFile(); if (!outFile.exists()) { if (!createDirs) { error = "Output directory '" + outFile.getAbsolutePath() + " does not exist', " + "skipping extraction of '" + outName + "'!"; System.err.println(error); errors.append(error + "\n"); break; } else { if (!outFile.mkdirs()) { error = "Failed to create directory '" + outFile.getAbsolutePath() + "', " + "skipping extraction of '" + outName + "'!"; System.err.println(error); errors.append(error + "\n"); break; } } } // extract data in = new BufferedInputStream(zipfile.getInputStream(entry)); fos = new FileOutputStream(outName); out = new BufferedOutputStream(fos, bufferSize); read = 0; while (read < entry.getSize()) { len = in.read(buffer); read += len; out.write(buffer, 0, len); } result = true; break; } catch (Exception e) { result = false; error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e; System.err.println(error); errors.append(error + "\n"); } finally { FileUtils.closeQuietly(in); FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } } } catch (Exception e) { result = false; e.printStackTrace(); errors.append("Error occurred: " + e + "\n"); } finally { if (zipfile != null) { try { zipfile.close(); } catch (Exception e) { // ignored } } } return result; }
From source file:ee.sk.digidoc.SignedDoc.java
public InputStream findDataFileAsStream(String dfName) { try {// www . j ava2s.c o m if (m_file != null) { StringBuffer sbName = new StringBuffer(); if (m_path != null) { sbName.append(m_path); sbName.append(File.separator); } sbName.append(m_file); File fZip = new File(sbName.toString()); if (fZip.isFile() && fZip.canRead()) { ZipFile zis = new ZipFile(fZip); ZipArchiveEntry ze = zis.getEntry(dfName); if (ze != null) { return zis.getInputStream(ze); } } } } catch (Exception ex) { m_logger.error("Error reading bdoc: " + ex); } return null; }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Apply delta.//from w w w. j a v a2 s.com * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException( fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream .read(sourceBytes, erg, sourceBytes.length - erg)) ; } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } }
From source file:at.spardat.xma.xdelta.JarDelta.java
/** * Compute delta.//from w w w . j a v a 2 s. com * * @param source the source * @param target the target * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list, String prefix) throws IOException { try { for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) { calculatedDelta = null; ZipArchiveEntry targetEntry = enumer.nextElement(); ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry); String nextEntryName = prefix + targetEntry.getName(); if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches() && !equal(sourceEntry, targetEntry)) { nextEntryName += "!"; } nextEntryName += "|" + Long.toHexString(targetEntry.getCrc()); if (sourceEntry != null) { nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc()); } else { nextEntryName += ":0"; } list.println(nextEntryName); if (targetEntry.isDirectory()) { if (sourceEntry == null) { ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName()); output.putArchiveEntry(outputEntry); output.closeArchiveEntry(); } } else { if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName()); output.putArchiveEntry(outputEntry); try (InputStream in = target.getInputStream(targetEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); } output.closeArchiveEntry(); } else { if (!equal(sourceEntry, targetEntry)) { if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) { File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip"); File embeddedSource = File.createTempFile("jardelta-tmp", ".zip"); try (FileOutputStream out = new FileOutputStream(embeddedSource); InputStream in = source.getInputStream(sourceEntry); FileOutputStream out2 = new FileOutputStream(embeddedTarget); InputStream in2 = target.getInputStream(targetEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); read = 0; while (-1 < (read = in2.read(buffer))) { out2.write(buffer, 0, read); } out2.flush(); computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output, list, prefix + sourceEntry.getName() + "!"); } finally { embeddedSource.delete(); embeddedTarget.delete(); } } else { ZipArchiveEntry outputEntry = new ZipArchiveEntry( prefix + targetEntry.getName() + ".gdiff"); outputEntry.setTime(targetEntry.getTime()); outputEntry.setComment("" + targetEntry.getCrc()); output.putArchiveEntry(outputEntry); if (calculatedDelta != null) { output.write(calculatedDelta); output.flush(); } else { try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) { Delta d = new Delta(); DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes)); int sourceSize = (int) sourceEntry.getSize(); byte[] sourceBytes = new byte[sourceSize]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream.read( sourceBytes); erg < sourceBytes.length; erg += sourceStream .read(sourceBytes, erg, sourceBytes.length - erg)) ; } d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter); output.write(outbytes.toByteArray()); } } output.closeArchiveEntry(); } } } } } } finally { source.close(); target.close(); } }
From source file:adams.core.io.ZipUtils.java
/** * Unzips the files in a ZIP file. Files can be filtered based on their * filename, using a regular expression (the matching sense can be inverted). * * @param input the ZIP file to unzip/*from www . ja v a 2 s .c o m*/ * @param outputDir the directory where to store the extracted files * @param createDirs whether to re-create the directory structure from the * ZIP file * @param match the regular expression that the files are matched against * @param invertMatch whether to invert the matching sense * @param bufferSize the buffer size to use * @param errors for storing potential errors * @return the successfully extracted files */ @MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html") public static List<File> decompress(File input, File outputDir, boolean createDirs, BaseRegExp match, boolean invertMatch, int bufferSize, StringBuilder errors) { List<File> result; ZipFile archive; Enumeration<ZipArchiveEntry> enm; ZipArchiveEntry entry; File outFile; String outName; byte[] buffer; BufferedInputStream in; BufferedOutputStream out; FileOutputStream fos; int len; String error; long read; result = new ArrayList<>(); archive = null; try { // unzip archive buffer = new byte[bufferSize]; archive = new ZipFile(input.getAbsoluteFile()); enm = archive.getEntries(); while (enm.hasMoreElements()) { entry = enm.nextElement(); if (entry.isDirectory() && !createDirs) continue; // does name match? if (!match.isMatchAll() && !match.isEmpty()) { if (invertMatch && match.isMatch(entry.getName())) continue; else if (!invertMatch && !match.isMatch(entry.getName())) continue; } // extract if (entry.isDirectory() && createDirs) { outFile = new File(outputDir.getAbsolutePath() + File.separator + entry.getName()); if (!outFile.mkdirs()) { error = "Failed to create directory '" + outFile.getAbsolutePath() + "'!"; System.err.println(error); errors.append(error + "\n"); } } else { in = null; out = null; fos = null; outName = null; try { // assemble output name outName = outputDir.getAbsolutePath() + File.separator; if (createDirs) outName += entry.getName(); else outName += new File(entry.getName()).getName(); // create directory, if necessary outFile = new File(outName).getParentFile(); if (!outFile.exists()) { if (!outFile.mkdirs()) { error = "Failed to create directory '" + outFile.getAbsolutePath() + "', " + "skipping extraction of '" + outName + "'!"; System.err.println(error); errors.append(error + "\n"); continue; } } // extract data in = new BufferedInputStream(archive.getInputStream(entry)); fos = new FileOutputStream(outName); out = new BufferedOutputStream(fos, bufferSize); read = 0; while (read < entry.getSize()) { len = in.read(buffer); read += len; out.write(buffer, 0, len); } result.add(new File(outName)); } catch (Exception e) { error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e; System.err.println(error); errors.append(error + "\n"); } finally { FileUtils.closeQuietly(in); FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } } } } catch (Exception e) { e.printStackTrace(); errors.append("Error occurred: " + e + "\n"); } finally { if (archive != null) { try { archive.close(); } catch (Exception e) { // ignored } } } return result; }
From source file:com.naryx.tagfusion.expression.function.file.Unzip.java
private void performUnzip(cfSession _session, File _zipfile, File _destination, String charset, boolean _flatten, boolean overwrite) throws cfmRunTimeException { ZipFile zFile = null; try {/*from ww w .java 2s . c om*/ zFile = new ZipFile(_zipfile, charset); } catch (IOException ze) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } BufferedInputStream in = null; InputStream zIn = null; FileOutputStream fout = null; File nextFile = null; String destinationFilename; byte[] buffer = new byte[4096]; int read; try { Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries(); if (files == null) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } ZipArchiveEntry nextEntry; // while unzip stuff goes here while (files.hasMoreElements()) { nextEntry = files.nextElement(); destinationFilename = nextEntry.getName(); File checkFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); if (checkFile.exists() && !overwrite) { throwException(_session, "File already exist"); } else { if (!nextEntry.isDirectory()) { if (_flatten) { int pathEnd = destinationFilename.lastIndexOf('/'); if (pathEnd != -1) destinationFilename = destinationFilename.substring(pathEnd + 1); } nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { } // use original nextFile if getCanonicalFile() fails File parent = nextFile.getParentFile(); if (parent != null) { parent.mkdirs(); // create the parent directory structure if needed } try { zIn = zFile.getInputStream(nextEntry); in = new BufferedInputStream(zIn); fout = new FileOutputStream(nextFile, false); while ((read = in.read(buffer)) != -1) { fout.write(buffer, 0, read); } fout.flush(); } catch (IOException ioe) { throwException(_session, "Failed to extract entry [" + nextEntry.getName() + "] from zip file to " + nextFile.getAbsolutePath() + ". Check the permissions are suitable to allow this file to be written."); } finally { StreamUtil.closeStream(in); StreamUtil.closeStream(zIn); StreamUtil.closeStream(fout); } } else if (!_flatten) { destinationFilename = nextEntry.getName(); nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { // use original nextFile if getCanonicalFile() fails } nextFile.mkdirs(); } } } } finally { try { zFile.close(); } catch (IOException ignored) { } } }
From source file:com.igormaznitsa.mvngolang.utils.UnpackUtils.java
public static int unpackFileToFolder(@Nonnull final Log logger, @Nullable final String folder, @Nonnull final File archiveFile, @Nonnull final File destinationFolder, final boolean makeAllExecutable) throws IOException { final String normalizedName = archiveFile.getName().toLowerCase(Locale.ENGLISH); final ArchEntryGetter entryGetter; boolean modeZipFile = false; final ZipFile theZipFile; final ArchiveInputStream archInputStream; if (normalizedName.endsWith(".zip")) { logger.debug("Detected ZIP archive"); modeZipFile = true;//from w w w.ja v a 2 s . c o m theZipFile = new ZipFile(archiveFile); archInputStream = null; entryGetter = new ArchEntryGetter() { private final Enumeration<ZipArchiveEntry> iterator = theZipFile.getEntries(); @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { ArchiveEntry result = null; if (this.iterator.hasMoreElements()) { result = this.iterator.nextElement(); } return result; } }; } else { theZipFile = null; final InputStream in = new BufferedInputStream(new FileInputStream(archiveFile)); try { if (normalizedName.endsWith(".tar.gz")) { logger.debug("Detected TAR.GZ archive"); archInputStream = new TarArchiveInputStream(new GZIPInputStream(in)); entryGetter = new ArchEntryGetter() { @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { return ((TarArchiveInputStream) archInputStream).getNextTarEntry(); } }; } else { logger.debug("Detected OTHER archive"); archInputStream = ARCHIVE_STREAM_FACTORY.createArchiveInputStream(in); logger.debug("Created archive stream : " + archInputStream.getClass().getName()); entryGetter = new ArchEntryGetter() { @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { return archInputStream.getNextEntry(); } }; } } catch (ArchiveException ex) { IOUtils.closeQuietly(in); throw new IOException("Can't recognize or read archive file : " + archiveFile, ex); } catch (CantReadArchiveEntryException ex) { IOUtils.closeQuietly(in); throw new IOException("Can't read entry from archive file : " + archiveFile, ex); } } try { final String normalizedFolder = folder == null ? null : FilenameUtils.normalize(folder, true) + '/'; int unpackedFilesCounter = 0; while (true) { final ArchiveEntry entry = entryGetter.getNextEntry(); if (entry == null) { break; } final String normalizedPath = FilenameUtils.normalize(entry.getName(), true); logger.debug("Detected archive entry : " + normalizedPath); if (normalizedFolder == null || normalizedPath.startsWith(normalizedFolder)) { final File targetFile = new File(destinationFolder, normalizedFolder == null ? normalizedPath : normalizedPath.substring(normalizedFolder.length())); if (entry.isDirectory()) { logger.debug("Folder : " + normalizedPath); if (!targetFile.exists() && !targetFile.mkdirs()) { throw new IOException("Can't create folder " + targetFile); } } else { final File parent = targetFile.getParentFile(); if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { throw new IOException("Can't create folder : " + parent); } final FileOutputStream fos = new FileOutputStream(targetFile); try { if (modeZipFile) { logger.debug("Unpacking ZIP entry : " + normalizedPath); final InputStream zipEntryInStream = theZipFile .getInputStream((ZipArchiveEntry) entry); try { if (IOUtils.copy(zipEntryInStream, fos) != entry.getSize()) { throw new IOException( "Can't unpack file, illegal unpacked length : " + entry.getName()); } } finally { IOUtils.closeQuietly(zipEntryInStream); } } else { logger.debug("Unpacking archive entry : " + normalizedPath); if (!archInputStream.canReadEntryData(entry)) { throw new IOException("Can't read archive entry data : " + normalizedPath); } if (IOUtils.copy(archInputStream, fos) != entry.getSize()) { throw new IOException( "Can't unpack file, illegal unpacked length : " + entry.getName()); } } } finally { fos.close(); } if (makeAllExecutable) { try { targetFile.setExecutable(true, true); } catch (SecurityException ex) { throw new IOException("Can't make file executable : " + targetFile, ex); } } unpackedFilesCounter++; } } else { logger.debug("Archive entry " + normalizedPath + " ignored"); } } return unpackedFilesCounter; } finally { IOUtils.closeQuietly(theZipFile); IOUtils.closeQuietly(archInputStream); } }
From source file:com.android.sdklib.internal.repository.ArchiveInstaller.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. * This root folder is skipped when unarchiving. *//*from w w w. j av a 2 s . c o m*/ @SuppressWarnings("unchecked") private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description, ITaskMonitor monitor) { description += " (%1$d%%)"; ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // figure if we'll need to set the unix permissions boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX; // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory // (e.g. docs/index.html). However we want to use our top-level // directory so we drop the first segment of the path name. int pos = name.indexOf('/'); if (pos < 0 || pos == name.length() - 1) { continue; } else { name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!destFile.isDirectory() && !destFile.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!parentDir.isDirectory()) { if (!parentDir.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; try { fos = new FileOutputStream(destFile); int n; InputStream entryContent = zipFile.getInputStream(entry); while ((n = entryContent.read(buf)) != -1) { if (n > 0) { fos.write(buf, 0, n); } } } finally { if (fos != null) { fos.close(); } } // if needed set the permissions. if (usingUnixPerm && destFile.isFile()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); if ((mode & 0111) != 0) { OsHelper.setExecutablePermission(destFile); } } // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription(description, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.setResult("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }
From source file:com.android.sdklib.internal.repository.Archive.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. This root folder is skipped when * unarchiving. However we return that root folder name to the caller, as it can be used * as a template to know what destination directory to use in the Add-on case. *//*from www .j a va 2s . c o m*/ @SuppressWarnings("unchecked") private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description, String[] outZipRootFolder, ITaskMonitor monitor) { description += " (%1$d%%)"; ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // figure if we'll need to set the unix permission boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX; // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory // (e.g. docs/index.html). However we want to use our top-level // directory so we drop the first segment of the path name. int pos = name.indexOf('/'); if (pos < 0 || pos == name.length() - 1) { continue; } else { if (outZipRootFolder[0] == null && pos > 0) { outZipRootFolder[0] = name.substring(0, pos); } name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!destFile.isDirectory() && !destFile.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!parentDir.isDirectory()) { if (!parentDir.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; try { fos = new FileOutputStream(destFile); int n; InputStream entryContent = zipFile.getInputStream(entry); while ((n = entryContent.read(buf)) != -1) { if (n > 0) { fos.write(buf, 0, n); } } } finally { if (fos != null) { fos.close(); } } // if needed set the permissions. if (usingUnixPerm && destFile.isFile()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); if ((mode & 0111) != 0) { setExecutablePermission(destFile); } } // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription(description, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.setResult("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }