List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(String name) throws IOException
From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftExporterBeanTest.java
@Test public void testExportArchiveZip() throws Exception { final Project p = makeGoodProject(); final List<PackagingInfo> infos = this.bean.getAvailablePackagingInfos(p); final PackagingInfo zipPi = Iterables.find(infos, new Predicate<PackagingInfo>() { @Override// ww w. j a v a 2s .c o m public boolean apply(PackagingInfo t) { return t.getMethod() == PackagingInfo.PackagingMethod.ZIP; } }); final File f = File.createTempFile("test", zipPi.getName()); final FileOutputStream fos = new FileOutputStream(f); this.bean.export(p, "http://example.com/my_experiemnt", PackagingInfo.PackagingMethod.ZIP, fos); fos.close(); final ZipFile zf = new ZipFile(f); final Enumeration<ZipArchiveEntry> en = zf.getEntries(); final Set<String> entries = new HashSet<String>(); entries.addAll(java.util.Arrays.asList("test-exp-id.soft.txt", "raw_file.data", "derived_file.data", "supplimental.data")); while (en.hasMoreElements()) { final ZipArchiveEntry ze = en.nextElement(); assertTrue(ze.getName() + " unexpected", entries.remove(ze.getName())); } assertTrue(entries.toString() + " not found", entries.isEmpty()); }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * zip?// ww w . j a va2s . c om * * @param zipFile * @param pathName * @return */ public static boolean isFolderExist(File zipFile, String pathName) { ZipFile file = null; try { file = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> en = file.getEntries(); while (en.hasMoreElements()) { ZipArchiveEntry entry = en.nextElement(); String name = entry.getName(); if (name.startsWith(pathName)) { return true; } } return false; } catch (IOException e) { } finally { if (null != file) { try { file.close(); } catch (IOException e) { } } } return false; }
From source file:com.android.tradefed.targetprep.FastbootDeviceFlasher.java
/** * Extracts the userdata.img from device image file and flashes it onto device * @param device the {@link ITestDevice} to flash * @param deviceBuild the {@link IDeviceBuildInfo} that contains the files to flash * @throws DeviceNotAvailableException if device is not available * @throws TargetSetupError if failed to extract or flash user data *//*from ww w. java 2 s .c om*/ protected void flashUserDataFromDeviceImageFile(ITestDevice device, IDeviceBuildInfo deviceBuild) throws DeviceNotAvailableException, TargetSetupError { File userdataImg = null; try { try (ZipFile zip = new ZipFile(deviceBuild.getDeviceImageFile())) { userdataImg = ZipUtil2.extractFileFromZip(zip, "userdata.img"); } catch (IOException ioe) { throw new TargetSetupError("failed to extract userdata.img from image file", ioe, device.getDeviceDescriptor()); } CLog.i("Flashing %s with userdata %s", device.getSerialNumber(), userdataImg); flashPartition(device, userdataImg, "userdata"); } finally { FileUtil.deleteFile(userdataImg); } }
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 2s.co 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.taobao.android.tpatch.utils.PatchUtils.java
/** * ?so?bundle/*from w w w . j a v a2s. c o m*/ * * @param soFile * @return */ public static boolean isBundleFile(File soFile) { ZipFile zf = null; try { zf = new ZipFile(soFile); Enumeration<ZipArchiveEntry> en = zf.getEntries(); if (en.hasMoreElements()) { for (String name : BUNDLE_FILES) { ZipArchiveEntry zipArchiveEntry = zf.getEntry(name); if (null == zipArchiveEntry) { return false; } } return true; } return false; } catch (IOException e) { return false; } finally { if (null != zf) { try { zf.close(); } catch (IOException e) { } } } }
From source file:ee.sk.digidoc.SignedDoc.java
public InputStream findDataFileAsStream(String dfName) { try {/*from w ww. j a v a 2 s . co 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:com.taobao.android.builder.tools.zip.ZipUtils.java
public static List<String> unzip(final File zipFile, final String destination, String encoding, Map<String, ZipEntry> zipEntryMethodMap, boolean isRelativePath) { List<String> fileNames = new ArrayList<String>(); String dest = destination;//from w w w . j a v a 2 s . c om if (!destination.endsWith(File.separator)) { dest = destination + File.separator; } ZipFile file; try { file = null; if (null == encoding) { file = new ZipFile(zipFile); } else { file = new ZipFile(zipFile, encoding); } Enumeration<ZipArchiveEntry> en = file.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); File f = new File(dest, ze.getName()); if (ze.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); InputStream is = file.getInputStream(ze); OutputStream os = new FileOutputStream(f); IOUtils.copy(is, os); is.close(); os.close(); fileNames.add(f.getAbsolutePath()); if (zipEntryMethodMap != null && ze.getMethod() == STORED) { zipEntryMethodMap.put(isRelativePath ? ze.getName() : f.getAbsolutePath(), ze); } } } file.close(); } catch (IOException e) { e.printStackTrace(); } return fileNames; }
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. */// www .j av a 2s .co 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; }
From source file:com.android.tools.idea.sdk.remote.internal.archives.ArchiveInstaller.java
/** * Unzips a zip file into the given destination directory. * <p/>/*ww w . j a v a2 s . co m*/ * The archive file MUST have a unique "root" folder. * This root folder is skipped when unarchiving. */ @SuppressWarnings("unchecked") @VisibleForTesting(visibility = Visibility.PRIVATE) protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder, ITaskMonitor monitor) { Archive newArchive = archiveInfo.getNewArchive(); RemotePkgInfo pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); long compressedSize = newArchive.getSize(); ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // 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). int pos = name.indexOf('/'); if (pos == -1) { // All zip entries should have a root folder. // This zip entry seems located at the root of the zip. // Rather than ignore the file, just place it at the root. } else if (pos == name.length() - 1) { // This is a zip *directory* entry in the form dir/, so essentially // it's the root directory of the SDK. It's safe to ignore that one // since we want to use our own root directory and we'll recreate // root directories as needed. // A direct consequence is that if a malformed archive has multiple // root directories, their content will all be merged together. continue; } else { // This is the expected behavior: the zip entry is in the form root/file // or root/dir/. We want to use our top-level directory so we drop the // first segment of the path name. 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 (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) { monitor.logError("Failed to create directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Sanity check: since we're always unzipping in a fresh temp folder // the destination file shouldn't already exist. if (mFileOp.exists(destFile)) { monitor.logVerbose("Duplicate file found: %1$s", name); } // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!mFileOp.isDirectory(parentDir)) { if (!mFileOp.mkdirs(parentDir)) { monitor.logError("Failed to create directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; long remains = entry.getSize(); try { fos = new FileOutputStream(destFile); // Java bug 4040920: do not rely on the input stream EOF and don't // try to read more than the entry's size. InputStream entryContent = zipFile.getInputStream(entry); int n; while (remains > 0 && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) { remains -= n; if (n > 0) { fos.write(buf, 0, n); } } } catch (EOFException e) { monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.", entry.getName(), entry.getSize(), remains); throw e; } finally { if (fos != null) { fos.close(); } } pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry); // 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("Unzipping %1$s (%2$d%%)", pkgName, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.logError("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.archives.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 .jav a 2s .c o m*/ @SuppressWarnings("unchecked") @VisibleForTesting(visibility = Visibility.PRIVATE) protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder, ITaskMonitor monitor) { Archive newArchive = archiveInfo.getNewArchive(); Package pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); long compressedSize = newArchive.getSize(); ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // 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). int pos = name.indexOf('/'); if (pos == -1) { // All zip entries should have a root folder. // This zip entry seems located at the root of the zip. // Rather than ignore the file, just place it at the root. } else if (pos == name.length() - 1) { // This is a zip *directory* entry in the form dir/, so essentially // it's the root directory of the SDK. It's safe to ignore that one // since we want to use our own root directory and we'll recreate // root directories as needed. // A direct consequence is that if a malformed archive has multiple // root directories, their content will all be merged together. continue; } else { // This is the expected behavior: the zip entry is in the form root/file // or root/dir/. We want to use our top-level directory so we drop the // first segment of the path name. 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 (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) { monitor.logError("Failed to create directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Sanity check: since we're always unzipping in a fresh temp folder // the destination file shouldn't already exist. if (mFileOp.exists(destFile)) { monitor.logVerbose("Duplicate file found: %1$s", name); } // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!mFileOp.isDirectory(parentDir)) { if (!mFileOp.mkdirs(parentDir)) { monitor.logError("Failed to create directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; long remains = entry.getSize(); try { fos = new FileOutputStream(destFile); // Java bug 4040920: do not rely on the input stream EOF and don't // try to read more than the entry's size. InputStream entryContent = zipFile.getInputStream(entry); int n; while (remains > 0 && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) { remains -= n; if (n > 0) { fos.write(buf, 0, n); } } } catch (EOFException e) { monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.", entry.getName(), entry.getSize(), remains); throw e; } finally { if (fos != null) { fos.close(); } } pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry); // 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("Unzipping %1$s (%2$d%%)", pkgName, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.logError("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }