List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry isDirectory
public boolean isDirectory()
From source file:com.taobao.android.utils.ZipUtils.java
/** * <p>//from w w w . ja v a 2s . com * unzip. * </p> * * @param zipFile a {@link File} object. * @param destination a {@link String} object. * @param encoding a {@link String} object. * @return a {@link List} object. */ public static List<String> unzip(final File zipFile, final String destination, String encoding) { List<String> fileNames = new ArrayList<String>(); String dest = destination; if (!destination.endsWith("/")) { dest = destination + "/"; } 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()); } } file.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return fileNames; }
From source file:io.webfolder.cdp.ChromiumDownloader.java
private static void unpack(File archive, File destionation) throws IOException { try (ZipFile zip = new ZipFile(archive)) { Map<File, String> symLinks = new LinkedHashMap<>(); Enumeration<ZipArchiveEntry> iterator = zip.getEntries(); // Top directory name we are going to ignore String parentDirectory = iterator.nextElement().getName(); // Iterate files & folders while (iterator.hasMoreElements()) { ZipArchiveEntry entry = iterator.nextElement(); String name = entry.getName().substring(parentDirectory.length()); File outputFile = new File(destionation, name); if (name.startsWith("interactive_ui_tests")) { continue; }//from w ww . j a v a 2s. com if (entry.isUnixSymlink()) { symLinks.put(outputFile, zip.getUnixSymlink(entry)); } else if (!entry.isDirectory()) { if (!outputFile.getParentFile().isDirectory()) { outputFile.getParentFile().mkdirs(); } try (FileOutputStream outStream = new FileOutputStream(outputFile)) { IOUtils.copy(zip.getInputStream(entry), outStream); } } // Set permission if (!entry.isUnixSymlink() && outputFile.exists()) try { Files.setPosixFilePermissions(outputFile.toPath(), modeToPosixPermissions(entry.getUnixMode())); } catch (Exception e) { // ignore } } for (Map.Entry<File, String> entry : symLinks.entrySet()) { try { Path source = Paths.get(entry.getKey().getAbsolutePath()); Path target = source.getParent().resolve(entry.getValue()); if (!source.toFile().exists()) Files.createSymbolicLink(source, target); } catch (Exception e) { // ignore } } } }
From source file:adams.core.io.ZipUtils.java
/** * Lists the files stored in the ZIP file. * * @param input the ZIP file to obtain the file list from * @param listDirs whether to include directories in the list * @return the stored files/*from w w w. j av a2s. c om*/ */ public static List<File> listFiles(File input, boolean listDirs) { List<File> result; ZipFile zipfile; Enumeration<ZipArchiveEntry> enm; ZipArchiveEntry entry; result = new ArrayList<>(); zipfile = null; try { zipfile = new ZipFile(input.getAbsoluteFile()); enm = zipfile.getEntries(); while (enm.hasMoreElements()) { entry = enm.nextElement(); // extract if (entry.isDirectory()) { if (listDirs) result.add(new File(entry.getName())); } else { result.add(new File(entry.getName())); } } } catch (Exception e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (Exception e) { // ignored } } } return result; }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * <p>// w w w . j a v a 2s . c o m * unzip. * </p> * * @param zipFile a {@link java.io.File} object. * @param destination a {@link String} object. * @param encoding a {@link String} object. * @return a {@link java.util.List} object. */ public static List<String> unzip(final File zipFile, final String destination, String encoding) { List<String> fileNames = new ArrayList<String>(); String dest = destination; 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()); } } file.close(); } catch (IOException e) { e.printStackTrace(); } return fileNames; }
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;/*ww w. j a v a 2s . co m*/ 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.repository.util.InstallerUtil.java
/** * Unzips the given zipped input stream into the given directory. * * @param in The (zipped) input stream. * @param out The directory into which to expand the files. Must exist. * @param fop The {@link FileOp} to use for file operations. * @param expectedSize Compressed size of the stream. * @param progress Currently only used for logging. * @throws IOException If we're unable to read or write. *//*from w w w . ja va2 s. co m*/ public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize, @NonNull ProgressIndicator progress) throws IOException { if (!fop.exists(out) || !fop.isDirectory(out)) { throw new IllegalArgumentException("out must exist and be a directory."); } // ZipFile requires an actual (not mock) file, so make sure we have a real one. in = fop.ensureRealFile(in); progress.setText("Unzipping..."); ZipFile zipFile = new ZipFile(in); try { Enumeration entries = zipFile.getEntries(); progress.setFraction(0); while (entries.hasMoreElements()) { ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(out, name); progress.setSecondaryText(name); if (entry.isUnixSymlink()) { ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream(); readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress); Path linkPath = fop.toPath(entryFile); Path linkTarget = fop.toPath(new File(targetByteStream.toString())); Files.createSymbolicLink(linkPath, linkTarget); } else if (entry.isDirectory()) { if (!fop.exists(entryFile)) { if (!fop.mkdirs(entryFile)) { progress.logWarning("failed to mkdirs " + entryFile); } } } else { if (!fop.exists(entryFile)) { File parent = entryFile.getParentFile(); if (parent != null && !fop.exists(parent)) { fop.mkdirs(parent); } if (!fop.createNewFile(entryFile)) { throw new IOException("Failed to create file " + entryFile); } } OutputStream unzippedOutput = fop.newFileOutputStream(entryFile); if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) { return; } if (!fop.isWindows()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); //noinspection OctalInteger if ((mode & 0111) != 0) { try { fop.setExecutablePermission(entryFile); } catch (IOException ignore) { } } } } } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:de.crowdcode.movmvn.core.Unzipper.java
/** * Unzip a file./*from www . j av a 2 s . co m*/ * * @param archiveFile * to be unzipped * @param outPath * the place to put the result * @throws IOException * exception * @throws ZipException * exception */ public void unzipFileToDir(final File archiveFile, final File outPath) throws IOException, ZipException { ZipFile zipFile = new ZipFile(archiveFile); Enumeration<ZipArchiveEntry> e = zipFile.getEntries(); while (e.hasMoreElements()) { ZipArchiveEntry entry = e.nextElement(); File file = new File(outPath, entry.getName()); if (entry.isDirectory()) { FileUtils.forceMkdir(file); } else { InputStream is = zipFile.getInputStream(entry); FileOutputStream os = FileUtils.openOutputStream(file); try { IOUtils.copy(is, os); } finally { os.close(); is.close(); } file.setLastModified(entry.getTime()); } } }
From source file:adams.core.io.ZipUtils.java
/** * Unzips the specified file from a ZIP file. * * @param input the ZIP file to unzip//from w w w . j a 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:cn.vlabs.clb.server.utils.UnCompress.java
public void unzip(File file) { ZipFile zipfile = null;//from w w w . j a va 2s . c o m 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:com.facebook.buck.zip.Unzip.java
/** * Unzips a file to a destination and returns the paths of the written files. *///from ww w . j ava 2 s . c om public static ImmutableList<Path> extractZipFile(Path zipFile, ProjectFilesystem filesystem, Path relativePath, ExistingFileMode existingFileMode) throws IOException { // if requested, clean before extracting if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) { try (ZipFile zip = new ZipFile(zipFile.toFile())) { Enumeration<ZipArchiveEntry> entries = zip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); filesystem.deleteRecursivelyIfExists(relativePath.resolve(entry.getName())); } } } ImmutableList.Builder<Path> filesWritten = ImmutableList.builder(); try (ZipFile zip = new ZipFile(zipFile.toFile())) { Enumeration<ZipArchiveEntry> entries = zip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String fileName = entry.getName(); Path target = relativePath.resolve(fileName); // TODO(bolinfest): Keep track of which directories have already been written to avoid // making unnecessary Files.createDirectories() calls. In practice, a single zip file will // have many entries in the same directory. if (entry.isDirectory()) { // Create the directory and all its parent directories filesystem.mkdirs(target); } else { // Create parent folder filesystem.createParentDirs(target); filesWritten.add(target); // Write file try (InputStream is = zip.getInputStream(entry)) { if (entry.isUnixSymlink()) { filesystem.createSymLink(target, filesystem.getPath(new String(ByteStreams.toByteArray(is), Charsets.UTF_8)), /* force */ true); } else { try (OutputStream out = filesystem.newFileOutputStream(target)) { ByteStreams.copy(is, out); } } } // restore mtime for the file filesystem.resolve(target).toFile().setLastModified(entry.getTime()); // TODO(shs96c): Implement what the comment below says we should do. // // Sets the file permissions of the output file given the information in {@code entry}'s // extra data field. According to the docs at // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs: // // <pre> // The following is the layout of the ASi extra block for Unix. The // local-header and central-header versions are identical. // (Last Revision 19960916) // // Value Size Description // ----- ---- ----------- // (Unix3) 0x756e Short tag for this extra block type ("nu") // TSize Short total data size for this block // CRC Long CRC-32 of the remaining data // Mode Short file permissions // SizDev Long symlink'd size OR major/minor dev num // UID Short user ID // GID Short group ID // (var.) variable symbolic link filename // // Mode is the standard Unix st_mode field from struct stat, containing // user/group/other permissions, setuid/setgid and symlink info, etc. // </pre> // // From the stat man page, we see that the following mask values are defined for the file // permissions component of the st_mode field: // // <pre> // S_ISUID 0004000 set-user-ID bit // S_ISGID 0002000 set-group-ID bit (see below) // S_ISVTX 0001000 sticky bit (see below) // // S_IRWXU 00700 mask for file owner permissions // // S_IRUSR 00400 owner has read permission // S_IWUSR 00200 owner has write permission // S_IXUSR 00100 owner has execute permission // // S_IRWXG 00070 mask for group permissions // S_IRGRP 00040 group has read permission // S_IWGRP 00020 group has write permission // S_IXGRP 00010 group has execute permission // // S_IRWXO 00007 mask for permissions for others // (not in group) // S_IROTH 00004 others have read permission // S_IWOTH 00002 others have write permission // S_IXOTH 00001 others have execute permission // </pre> // // For the sake of our own sanity, we're going to assume that no-one is using symlinks, // but we'll check and throw if they are. // // Before we do anything, we should check the header ID. Pfft! // // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the // values in the external file attributes of a zip entry (found in the zip's central // directory) assuming that the OS creating the zip was one of an enormous list that // includes UNIX but not Windows, it first searches for the extra fields, and if not found // falls through to a code path that supports MS-DOS and which stores the UNIX file // attributes in the upper 16 bits of the external attributes field. // // We'll support neither approach fully, but we encode whether this file was executable // via storing 0100 in the fields that are typically used by zip implementations to store // POSIX permissions. If we find it was executable, use the platform independent java // interface to make this unpacked file executable. Set<PosixFilePermission> permissions = MorePosixFilePermissions .fromMode(entry.getExternalAttributes() >> 16); if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)) { MoreFiles.makeExecutable(filesystem.resolve(target)); } } } } return filesWritten.build(); }