List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(String name) throws IOException
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 va 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.tradefed.util.ZipUtil2.java
/** * Utility method to extract a zip file into a given directory. The zip file being presented as * a {@link File}.// ww w .j a va2s . c om * * @param zipFile a {@link File} pointing to a zip file. * @param destDir the local dir to extract file to * @throws IOException if failed to extract file */ public static void extractZip(File zipFile, File destDir) throws IOException { try (ZipFile zip = new ZipFile(zipFile)) { extractZip(zip, destDir); } }
From source file:cn.vlabs.clb.server.utils.UnCompress.java
public void unzip(File file) { ZipFile zipfile = null;//from ww w . ja v a2 s .com try { if (encoding == null) zipfile = new ZipFile(file); else zipfile = new ZipFile(file, encoding); Enumeration<ZipArchiveEntry> iter = zipfile.getEntries(); while (iter.hasMoreElements()) { ZipArchiveEntry entry = iter.nextElement(); if (!entry.isDirectory()) { InputStream entryis = null; try { entryis = zipfile.getInputStream(entry); listener.onNewEntry(new ZipEntryAdapter(entry, zipfile)); } finally { IOUtils.closeQuietly(entryis); } } } } catch (ZipException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error("file not found " + e.getMessage(), e); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { log.error(e); } } } }
From source file:io.github.zlika.reproducible.ZipStripper.java
@Override public void strip(File in, File out) throws IOException { try (final ZipFile zip = new ZipFile(in); final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) { final List<String> sortedNames = sortEntriesByName(zip.getEntries()); for (String name : sortedNames) { final ZipArchiveEntry entry = zip.getEntry(name); // Strip Zip entry final ZipArchiveEntry strippedEntry = filterZipEntry(entry); // Strip file if required final Stripper stripper = getSubFilter(name); if (stripper != null) { // Unzip entry to temp file final File tmp = File.createTempFile("tmp", null); tmp.deleteOnExit();/*ww w .j a va 2s .com*/ Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING); final File tmp2 = File.createTempFile("tmp", null); tmp2.deleteOnExit(); stripper.strip(tmp, tmp2); final byte[] fileContent = Files.readAllBytes(tmp2.toPath()); strippedEntry.setSize(fileContent.length); zout.putArchiveEntry(strippedEntry); zout.write(fileContent); zout.closeArchiveEntry(); } else { // Copy the Zip entry as-is zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry)); } } } }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void shouldZipSources() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();/* w ww.ja va 2s.c o m*/ Path zip = workspace.buildAndReturnOutput("//example:ziptastic"); // Make sure we have the right files and attributes. try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipArchiveEntry cake = zipFile.getEntry("cake.txt"); assertThat(cake, Matchers.notNullValue()); assertFalse(cake.isUnixSymlink()); assertFalse(cake.isDirectory()); ZipArchiveEntry beans = zipFile.getEntry("beans/"); assertThat(beans, Matchers.notNullValue()); assertFalse(beans.isUnixSymlink()); assertTrue(beans.isDirectory()); ZipArchiveEntry cheesy = zipFile.getEntry("beans/cheesy.txt"); assertThat(cheesy, Matchers.notNullValue()); assertFalse(cheesy.isUnixSymlink()); assertFalse(cheesy.isDirectory()); } }
From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.java
@Override public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException { progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN); String canonicalDestination = destination.toFile().getCanonicalPath(); // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to // all the zip file data and will return "0" for any call to getUnixMode(). try (ZipFile zipFile = new ZipFile(archive.toFile())) { // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count); Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries(); while (zipEntries.hasMoreElements()) { ZipArchiveEntry entry = zipEntries.nextElement(); Path entryTarget = destination.resolve(entry.getName()); String canonicalTarget = entryTarget.toFile().getCanonicalPath(); if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) { throw new IOException("Blocked unzipping files outside destination: " + entry.getName()); }//w w w.j a v a 2 s. com progressListener.update(1); logger.fine(entryTarget.toString()); if (entry.isDirectory()) { if (!Files.exists(entryTarget)) { Files.createDirectories(entryTarget); } } else { if (!Files.exists(entryTarget.getParent())) { Files.createDirectories(entryTarget.getParent()); } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) { try (InputStream in = zipFile.getInputStream(entry)) { IOUtils.copy(in, out); PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget, PosixFileAttributeView.class); if (attributeView != null) { attributeView .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode())); } } } } } } progressListener.done(); }
From source file:es.ucm.fdi.util.archive.ZipFormat.java
public ArrayList<String> list(File source) throws IOException { assertIsZip(source);/*from ww w. j a v a 2 s.co m*/ ArrayList<String> paths = new ArrayList<String>(); try (ZipFile zf = new ZipFile(source)) { Enumeration entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry e = (ZipArchiveEntry) entries.nextElement(); String name = FileUtils.toCanonicalPath(e.getName()); if (e.isDirectory()) { continue; } paths.add(name); } } return paths; }
From source file:com.android.tradefed.util.ZipUtil2Test.java
@Test public void testExtractFileFromZip() throws Exception { final File zip = getTestDataFile("permission-test"); final String fileName = "rwxr-x--x"; ZipFile zipFile = null;// w w w . j a v a 2 s.c o m try { zipFile = new ZipFile(zip); File extracted = ZipUtil2.extractFileFromZip(zipFile, fileName); mTempFiles.add(extracted); verifyFilePermission(extracted, fileName); } finally { ZipFile.closeQuietly(zipFile); } }
From source file:net.orpiske.ssps.common.archive.zip.ZipArchive.java
/** * Decompress a file//from w w w . ja v a 2 s. c o m * @param source the source file to be uncompressed * @param destination the destination directory * @return the number of bytes read * @throws IOException for lower level I/O errors */ public long unpack(File source, File destination) throws IOException { ZipFile zipFile = null; long ret = 0; try { zipFile = new ZipFile(source); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); File outFile = new File(destination.getPath() + File.separator + entry.getName()); CompressedArchiveUtils.prepareDestination(outFile); if (!entry.isDirectory()) { ret += extractFile(zipFile, entry, outFile); } int mode = entry.getUnixMode(); PermissionsUtils.setPermissions(mode, outFile); } } finally { if (zipFile != null) { zipFile.close(); } } return ret; }
From source file:io.selendroid.builder.SelendroidServerBuilderTest.java
@Test public void testShouldBeAbleToCreateCustomizedAndroidApplicationXML() throws Exception { SelendroidServerBuilder builder = getDefaultBuilder(); builder.init(new DefaultAndroidApp(new File(APK_FILE))); builder.cleanUpPrebuildServer();//from ww w.jav a 2 s . co m File file = builder.createAndAddCustomizedAndroidManifestToSelendroidServer(); ZipFile zipFile = new ZipFile(file); ZipArchiveEntry entry = zipFile.getEntry("AndroidManifest.xml"); Assert.assertEquals(entry.getName(), "AndroidManifest.xml"); Assert.assertTrue("Expecting non empty AndroidManifest.xml file", entry.getSize() > 700); // Verify that apk is not yet signed CommandLine cmd = new CommandLine(AndroidSdk.aapt()); cmd.addArgument("list", false); cmd.addArgument(builder.getSelendroidServer().getAbsolutePath(), false); String output = ShellCommand.exec(cmd); assertResultDoesNotContainFile(output, "META-INF/CERT.RSA"); assertResultDoesNotContainFile(output, "META-INF/CERT.SF"); }