org.apache.commons.compress.archivers.zip.ZipFile类的使用及代码示例

x33g5p2x  于2022-02-05 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(1046)

本文整理了Java中org.apache.commons.compress.archivers.zip.ZipFile类的一些代码示例,展示了ZipFile类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ZipFile类的具体详情如下:
包路径:org.apache.commons.compress.archivers.zip.ZipFile
类名称:ZipFile

ZipFile介绍

[英]Replacement for java.util.ZipFile.

This class adds support for file name encodings other than UTF-8 (which is required to work on ZIP files created by native zip tools and is able to skip a preamble like the one found in self extracting archives. Furthermore it returns instances of org.apache.commons.compress.archivers.zip.ZipArchiveEntry instead of java.util.zip.ZipEntry.

It doesn't extend java.util.zip.ZipFile as it would have to reimplement all methods anyway. Like java.util.ZipFile, it uses SeekableByteChannel under the covers and supports compressed and uncompressed entries. As of Apache Commons Compress 1.3 it also transparently supports Zip64 extensions and thus individual entries and archives larger than 4 GB or with more than 65536 entries.

The method signatures mimic the ones of java.util.zip.ZipFile, with a couple of exceptions:

  • There is no getName method.
  • entries has been renamed to getEntries.
  • getEntries and getEntry return org.apache.commons.compress.archivers.zip.ZipArchiveEntry instances.
  • close is allowed to throw IOException.
    [中]替换java.util.ZipFile
    这个类增加了对UTF-8以外的文件名编码的支持(UTF-8是处理本机ZIP工具创建的ZIP文件所必需的,并且能够跳过像在自解压归档文件中找到的前导。此外,它还返回org.apache.commons.compress.archivers.zip.ZipArchiveEntry而不是java.util.zip.ZipEntry的实例。
    它不会扩展java.util.zip.ZipFile,因为它无论如何都必须重新实现所有方法。与java.util.ZipFile类似,它在封面下使用SeekableByteChannel,并支持压缩和未压缩的条目。从Apache Commons Compress 1.3开始,它还透明地支持Zip64扩展,因此单个条目和存档大于4GB或超过65536个条目。
    方法签名模仿java.util.zip.ZipFile的签名,但有几个例外:
    *没有getName方法。
    *条目已重命名为getEntries。
    *getEntries和getEntry返回org.apache.commons.compress.archivers.zip.ZipArchiveEntry个实例。
    *close允许抛出IOException。

代码示例

代码示例来源:origin: plutext/docx4j

log.info( "Couldn't find " + f.getPath() );
  zf = new ZipFile(f);
} catch (IOException ioe) {
  ioe.printStackTrace() ;
Enumeration entries = zf.getEntries();
while (entries.hasMoreElements()) {
  ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
  policePartSize(f, entry.getSize(), entry.getName());
  InputStream in = null;
  try {
    byte[] bytes =  getBytesFromInputStream( zf.getInputStream(entry) );
    policePartSize(f, bytes.length, entry.getName()); // in case earlier check ineffective
    partByteArrays.put(entry.getName(), new ByteArray(bytes) );
  } catch (PartTooLargeException e) {
   zf.close();
 } catch (IOException exc) {
   exc.printStackTrace();

代码示例来源:origin: jeremylong/DependencyCheck

ZipFile zip = null;
try {
  zip = new ZipFile(dependency.getActualFilePath());
  if (zip.getEntry("META-INF/MANIFEST.MF") != null
      || zip.getEntry("META-INF/maven") != null) {
    final Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
      final ZipArchiveEntry entry = entries.nextElement();
      if (!entry.isDirectory()) {
        final String name = entry.getName().toLowerCase();
        if (name.endsWith(".class")) {
          isJar = true;
  LOGGER.debug("Unable to unzip zip file '{}'", dependency.getFilePath(), ex);
} finally {
  ZipFile.closeQuietly(zip);

代码示例来源:origin: org.apache.commons/commons-compress

/**
 * Transfer selected entries from this zipfile to a given #ZipArchiveOutputStream.
 * Compression and all other attributes will be as in this file.
 * <p>This method transfers entries based on the central directory of the zip file.</p>
 *
 * @param target The zipArchiveOutputStream to write the entries to
 * @param predicate A predicate that selects which entries to write
 * @throws IOException on error
 */
public void copyRawEntries(final ZipArchiveOutputStream target, final ZipArchiveEntryPredicate predicate)
    throws IOException {
  final Enumeration<ZipArchiveEntry> src = getEntriesInPhysicalOrder();
  while (src.hasMoreElements()) {
    final ZipArchiveEntry entry = src.nextElement();
    if (predicate.test( entry)) {
      target.addRawArchiveEntry(entry, getRawInputStream(entry));
    }
  }
}

代码示例来源:origin: org.apache.poi/poi-ooxml

@Override
  public ZipArchiveEntry getEntry(final String path) {
   String normalizedPath = path.replace('\\', '/');

   final ZipArchiveEntry entry = zipArchive.getEntry(normalizedPath);
   if (entry != null) {
     return entry;
   }

   // the opc spec allows case-insensitive filename matching (see #49609)
   for (final ZipArchiveEntry ze : asIterable(asIterator(zipArchive.getEntries()))) {
     if (normalizedPath.equalsIgnoreCase(ze.getName().replace('\\','/'))) {
      return ze;
     }
   }

   return null;
  }
}

代码示例来源:origin: apache/tika

private static MediaType detectKmz(ZipFile zip) {
  boolean kmlFound = false;
  Enumeration<ZipArchiveEntry> entries = zip.getEntries();
  while (entries.hasMoreElements()) {
    ZipArchiveEntry entry = entries.nextElement();
    String name = entry.getName();
    if (!entry.isDirectory()
        && name.indexOf('/') == -1 && name.indexOf('\\') == -1) {
      if (name.endsWith(".kml") && !kmlFound) {
        kmlFound = true;
      } else {
        return null;
      }
    }
  }
  if (kmlFound) {
    return MediaType.application("vnd.google-earth.kmz");
  } else {
    return null;
  }
}

代码示例来源:origin: de.unkrig.commons/commons-file

@Override @Nullable public ArchiveEntry
getNextEntry() throws IOException {
  if (!this.entries.hasMoreElements()) {
    this.stream = null;
    return null;
  }
  ZipArchiveEntry zae = this.entries.nextElement();
  this.stream = this.zipFile.getInputStream(zae);
  return zae;
}

代码示例来源:origin: gradle.plugin.org.echocat.gradle.plugins/gradle-golang-plugin

public static void unZip(File file, File target) throws IOException {
    try (final ZipFile zipFile = new ZipFile(file)) {
      final Enumeration<ZipArchiveEntry> files = zipFile.getEntriesInPhysicalOrder();
      while (files.hasMoreElements()) {
        final ZipArchiveEntry entry = files.nextElement();
        final File entryFile = new File(target, REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).getCanonicalFile();
        if (entry.isDirectory()) {
          forceMkdir(entryFile);
        } else {
          forceMkdir(entryFile.getParentFile());
          try (final InputStream is = zipFile.getInputStream(entry)) {
            try (final OutputStream os = new FileOutputStream(entryFile)) {
              copy(is, os);
            }
          }
        }

      }
    }
  }
}

代码示例来源:origin: apache/tika

public static MediaType detect(ZipFile zipFile) {
  MediaType type = null;
  Enumeration<? extends ZipEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {
   ZipEntry entry = entries.nextElement();
   type = IWork13DocumentType.detectIfPossible(entry);
   if (type != null) return type;
  }
    // If we get here, we don't know what it is
  return UNKNOWN13.getType();
}

代码示例来源:origin: org.codehaus.plexus/plexus-archiver

try
  zipFile = new org.apache.commons.compress.archivers.zip.ZipFile( getSourceFile(), encoding, true );
  final Enumeration e = zipFile.getEntriesInPhysicalOrder();
  while ( e.hasMoreElements() )
    final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
    final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo( zipFile, ze );
    if ( !isSelected( ze.getName(), fileInfo ) )
    if ( ze.getName().startsWith( path ) )
      in = zipFile.getInputStream( ze );
                  ze.getName(), new Date( ze.getTime() ), ze.isDirectory(),
                  ze.getUnixMode() != 0 ? ze.getUnixMode() : null,
                  resolveSymlink( zipFile, ze ), getFileMappers() );
  zipFile.close();
  zipFile = null;
  IOUtils.closeQuietly( in );
  IOUtils.closeQuietly( zipFile );

代码示例来源:origin: cn.easyproject/easybackup

boolean flag=false;
try {
  zf = new ZipFile(zipFile); // 获得zip文件
  zos = new ZipArchiveOutputStream(temp_file);
  Enumeration<ZipArchiveEntry> ze = zf.getEntries(); //获得所有压缩选项
  while (ze.hasMoreElements()) { //循环写出压缩文件
    ZipArchiveEntry zae = ze.nextElement();
    zos.putArchiveEntry(zae);
    if (!zae.isDirectory()) {
      IOUtils.copy(zf.getInputStream(zae), zos); // 3写入
    zipDirectory(zos, newFile, newFile.getAbsolutePath());
  } else { // 压缩文件
    ZipArchiveEntry zae = new ZipArchiveEntry(newFile.getName());// 1创建
    IOUtils.copy(bis, zos); // 3写入
      zf.close(); // 关闭流
    }catch (Exception e) {
      logger.error("addNewFileToZip error.", e); //$NON-NLS-1$

代码示例来源:origin: awslabs/aws-codepipeline-plugin-for-jenkins

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);
      }
    }
  }
}

代码示例来源:origin: USPTO/PatentPublicData

@Override
public BufferedReader next() {
  while (hasNext()) {
    currentEntry = entries.nextElement();
    File entryFile = new File(currentEntry.getName());
    if (filter.accept(entryFile)) {
      currentRecCount++;
      LOGGER.info("Found {} file[{}]: {}", currentRecCount, filter, currentEntry.getName());
      try {
        return new BufferedReader(new InputStreamReader(zipFile.getInputStream(currentEntry)));
      } catch (ZipException e) {
        LOGGER.error("Error reading Zip File: {}", file, e);
      } catch (IOException e) {
        LOGGER.error("IOException when reading file: {}", file, e);
      }
    }
  }
  //throw new NoSuchElementException();
  throw new NoSuchElementException();
}

代码示例来源:origin: edu.jhu.hlt/acute

@Override
public byte[] next() {
 try {
  ZipArchiveEntry entry = this.iter.nextElement();
  try (InputStream in = this.zf.getInputStream(entry);) {
   byte[] bytes = IOUtils.toByteArray(in);
   return bytes;
  }
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: apache/tika

/**
 * OpenDocument files, along with EPub files and ASiC ones, have a 
 *  mimetype entry in the root of their Zip file. This entry contains
 *  the mimetype of the overall file, stored as a single string.  
 */
private static MediaType detectOpenDocument(ZipFile zip) {
  try {
    ZipArchiveEntry mimetype = zip.getEntry("mimetype");
    if (mimetype != null) {
      try (InputStream stream = zip.getInputStream(mimetype)) {
        return MediaType.parse(IOUtils.toString(stream, UTF_8));
      }
    } else {
      return null;
    }
  } catch (IOException e) {
    return null;
  }
}

代码示例来源:origin: org.apache.commons/commons-compress

@Override
  public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
    try (InputStream in = archive.getInputStream((ZipArchiveEntry) entry)) {
      IOUtils.copy(in, out);
    }
  }
}, targetDirectory);

代码示例来源:origin: IQSS/dataverse

InputStream is = null;
try {
  zf = new ZipFile(getBagFile(bagId));
  ZipArchiveEntry entry = zf.getEntry(getValidName(bagId) + "/manifest-sha1.txt");
  if (entry != null) {
    logger.info("SHA1 hashes used");
    hashtype = DataFile.ChecksumType.SHA1;
  } else {
    entry = zf.getEntry(getValidName(bagId) + "/manifest-sha512.txt");
    if (entry != null) {
      logger.info("SHA512 hashes used");
      hashtype = DataFile.ChecksumType.SHA512;
    } else {
      entry = zf.getEntry(getValidName(bagId) + "/manifest-sha256.txt");
      if (entry != null) {
        logger.info("SHA256 hashes used");
        hashtype = DataFile.ChecksumType.SHA256;
      } else {
        entry = zf.getEntry(getValidName(bagId) + "/manifest-md5.txt");
        if (entry != null) {
          logger.info("MD5 hashes used");
  is = zf.getInputStream(entry);
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  String line = br.readLine();
    line = br.readLine();

代码示例来源:origin: apache/tika

protected String readArchiveText(InputStream inputStream) throws IOException {
  Path tempFile = writeTemporaryArchiveFile(inputStream, "zip");
  ZipFile zip = new ZipFile(tempFile.toFile());
  zip.getEntry(UnpackerResource.TEXT_FILENAME);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  IOUtils.copy(zip.getInputStream(zip.getEntry(UnpackerResource.TEXT_FILENAME)), bos);
  zip.close();
  Files.delete(tempFile);
  return bos.toString(UTF_8.name());
}

代码示例来源:origin: org.apache.commons/commons-compress

@Override
  public InputStream getInputStream() throws IOException {
    return in.getInputStream(current);
  }
}

代码示例来源:origin: org.webjars/webjars-locator-core

private void copyZipEntry(ZipFile zipFile, ZipArchiveEntry entry, File copyTo, String key) throws IOException {
  Cacheable forCache = new Cacheable(entry.getName(), entry.getTime());
  log.debug("Checking whether {} is up to date at {}", entry.getName(), copyTo);
  // Check for modification
  if (!copyTo.exists() || !cache.isUpToDate(key, forCache)) {
    log.debug("Up to date check failed, copying {} to {}", entry.getName(), copyTo);
    ensureIsDirectory(copyTo.getParentFile());
    copyAndClose(zipFile.getInputStream(entry), copyTo);
    if (SystemUtils.IS_OS_UNIX) {
      int mode = entry.getUnixMode();
      if (mode > 0) {
        Files.setPosixFilePermissions(copyTo.toPath(), toPerms(mode));
      }
    }
    cache.put(key, forCache);
  }
}

代码示例来源:origin: IQSS/dataverse

private String generateFileHash(String name, ZipFile zf) {
  ZipArchiveEntry archiveEntry1 = zf.getEntry(name);
  String realHash = null;
  try {
    inputStream = zf.getInputStream(archiveEntry1);
    if (hashtype.equals(DataFile.ChecksumType.SHA1)) {
      realHash = DigestUtils.sha1Hex(inputStream);
    IOUtils.closeQuietly(inputStream);
  bagGenerator.incrementTotalDataSize(archiveEntry1.getSize());
  return realHash;

相关文章