Java Code Examples for org.apache.commons.compress.archivers.zip.ZipFile#getInputStream()

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipFile#getInputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicExtractor.java    From embedded-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void extractZip(ZipFile zipFile) {
  Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();
    String fileName = entry.getName();
    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {
      makeDirectory(outputFile);
    } else {
      createNewFile(outputFile);
      try {
        InputStream inputStream = zipFile.getInputStream(entry);
        extractFile(inputStream, outputFile, fileName);
      } catch (IOException e) {
        throw new ExtractionException("Error extracting file '" + fileName + "' "
            + "from downloaded file: " + config.getDownloadTarget(), e);
      }
    }
  }
}
 
Example 2
Source File: ZipUtils.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
private void unzipEntry(final ZipFile zipfile, final ZipArchiveEntry entry, final File outputDir) throws IOException {

        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }

        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }

        try (BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
            IOUtils.copy(inputStream, outputStream);
        }
    }
 
Example 3
Source File: ExtractionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {
    final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        final File entryDestination = getDestinationFile(destination, entry.getName());

        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            final InputStream in = zipFile.getInputStream(entry);
            try (final OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}
 
Example 4
Source File: MavenDownloader.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public static void unzip(File zipFile, File destination)
        throws IOException {
    ZipFile zip = new ZipFile(zipFile);
    try {
        Enumeration<ZipArchiveEntry> e = zip.getEntries();
        while (e.hasMoreElements()) {
            ZipArchiveEntry entry = e.nextElement();
            File file = new File(destination, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = zip.getInputStream(entry);
                File parent = file.getParentFile();
                if (parent != null && parent.exists() == false) {
                    parent.mkdirs();
                }
                FileOutputStream os = new FileOutputStream(file);
                try {
                    IOUtils.copy(is, os);
                } finally {
                    os.close();
                    is.close();
                }
                file.setLastModified(entry.getTime());
                int mode = entry.getUnixMode();
                if ((mode & EXEC_MASK) != 0) {
                    if (!file.setExecutable(true)) {
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zip);
    }
}
 
Example 5
Source File: Zip.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private File unzipEntry(ZipFile zipFile, ZipArchiveEntry entry, Path targetDirectory,
        Consumer<ZipExtractionResult> unzipCallback) {
    final String fileName = entry.getName();
    final long compressedSize = entry.getCompressedSize();

    final Path targetPath = targetDirectory.resolve(fileName);
    try {
        if (entry.isDirectory()) {
            LOGGER.info(String.format("Attempting to create output directory %s.", targetPath.toString()));

            Files.createDirectories(targetPath);
        } else {
            Files.createDirectories(targetPath.getParent());

            try (InputStream in = zipFile.getInputStream(entry)) {
                LOGGER.info(String.format("Creating output file %s.", targetPath.toString()));

                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);

                // update progress bar
                unzipCallback.accept(new ZipExtractionResult(compressedSize, fileName));
            }
        }

        return targetPath.toFile();
    } catch (IOException e) {
        throw new ArchiveException(String.format("Unable to extract file \"%s\"", fileName), e);
    }
}
 
Example 6
Source File: Mq2Xliff.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
 * @param mqZip
 * @param hsSkeleton	R8 hsxliff的骨架文件
 * @throws Exception
 */
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
	ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
	Enumeration<?> e = zipFile.getEntries();
	byte ch[] = new byte[1024];
	String outputFile = "";
	File mqSklTempFile = File.createTempFile("tempskl", "skl");
	mqSklTempFile.deleteOnExit();
	while (e.hasMoreElements()) {
		ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
		if ("document.mqxliff".equals(zipEntry.getName())) {
			outputFile = hsSkeleton;
		}else {
			outputFile = mqSklTempFile.getAbsolutePath();
		}
		File zfile = new File(outputFile);
		FileOutputStream fouts = new FileOutputStream(zfile);
		InputStream in = zipFile.getInputStream(zipEntry);
		int i;
		while ((i = in.read(ch)) != -1)
			fouts.write(ch, 0, i);
		fouts.close();
		in.close();
	}
	
	//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
	parseHSSkeletonFile();
	copyMqSklToHsSkl(mqSklTempFile);
}
 
Example 7
Source File: BarFileInstaller.java    From io with Apache License 2.0 5 votes vote down vote up
private void checkAndReadManifest(String entryName, ZipArchiveEntry zae, ZipFile zipFile) throws IOException {
    InputStream inStream = zipFile.getInputStream(zae);
    try {
        JSONManifest manifest =
                BarFileUtils.readJsonEntry(inStream, entryName, JSONManifest.class);
        if (!manifest.checkSchema()) {
            throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName);
        }
        this.manifestJson = manifest.getJson();
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}
 
Example 8
Source File: Mq2Xliff.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
 * @param mqZip
 * @param hsSkeleton	R8 hsxliff的骨架文件
 * @throws Exception
 */
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
	ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
	Enumeration<?> e = zipFile.getEntries();
	byte ch[] = new byte[1024];
	String outputFile = "";
	File mqSklTempFile = File.createTempFile("tempskl", "skl");
	mqSklTempFile.deleteOnExit();
	while (e.hasMoreElements()) {
		ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
		if ("document.mqxliff".equals(zipEntry.getName())) {
			outputFile = hsSkeleton;
		}else {
			outputFile = mqSklTempFile.getAbsolutePath();
		}
		File zfile = new File(outputFile);
		FileOutputStream fouts = new FileOutputStream(zfile);
		InputStream in = zipFile.getInputStream(zipEntry);
		int i;
		while ((i = in.read(ch)) != -1)
			fouts.write(ch, 0, i);
		fouts.close();
		in.close();
	}
	
	//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
	parseHSSkeletonFile();
	copyMqSklToHsSkl(mqSklTempFile);
}
 
Example 9
Source File: Unzip.java    From buck with Apache License 2.0 4 votes vote down vote up
private void writeZipContents(
    ZipFile zip, ZipArchiveEntry entry, ProjectFilesystem filesystem, Path target)
    throws IOException {
  // 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);
      }
    }
  }

  Path filePath = filesystem.resolve(target);
  File file = filePath.toFile();

  // restore mtime for the file
  file.setLastModified(entry.getTime());

  // TODO(simons): 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)
      && file.getCanonicalFile().exists()) {
    MostFiles.makeExecutable(filePath);
  }
}