java.util.zip.ZipInputStream类的使用及代码示例

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

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

ZipInputStream介绍

[英]Used to read (decompress) the data from zip files.

A zip file (or "archive") is a collection of (possibly) compressed files. When reading from a ZipInputStream, you call #getNextEntrywhich returns a ZipEntry of metadata corresponding to the userdata that follows. When you appear to have hit the end of this stream (which is really just the end of the current entry's userdata), call getNextEntry again. When it returns null, there are no more entries in the input file.

Although InflaterInputStream can only read compressed zip entries, this class can read non-compressed entries as well.

Use ZipFile if you need random access to entries by name, but use this class if you just want to iterate over all entries.

Example

Using ZipInputStream is a little more complicated than GZIPInputStreambecause zip files are containers that can contain multiple files. This code pulls all the files out of a zip file, similar to the unzip(1) utility.

InputStream is = ... 
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); 
try { 
ZipEntry ze; 
while ((ze = zis.getNextEntry()) != null) { 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
byte[] buffer = new byte[1024]; 
int count; 
while ((count = zis.read(buffer)) != -1) { 
baos.write(buffer, 0, count); 
} 
String filename = ze.getName(); 
byte[] bytes = baos.toByteArray(); 
// do something with 'filename' and 'bytes'... 
} 
} finally { 
zis.close(); 
}

[中]用于从zip文件中读取(解压缩)数据。
zip文件(或“存档”)是(可能)压缩文件的集合。从ZipInputStream读取数据时,调用#GetNextery,它返回对应于后面的用户数据的元数据ZipEntry。当您似乎已经到达这个流的末尾(实际上只是当前条目的用户数据的末尾)时,再次调用getNextEntry。当它返回null时,输入文件中不再有条目。
尽管InflaterInputStream只能读取压缩的zip条目,但该类也可以读取非压缩的条目。
如果需要按名称随机访问条目,请使用ZipFile,但如果只想迭代所有条目,请使用此类。
####范例
使用ZipInputStream比GZipInputStream稍微复杂一些,因为zip文件是可以包含多个文件的容器。这段代码从一个zip文件中提取所有文件,类似于解压(1)实用程序。

InputStream is = ... 
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); 
try { 
ZipEntry ze; 
while ((ze = zis.getNextEntry()) != null) { 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
byte[] buffer = new byte[1024]; 
int count; 
while ((count = zis.read(buffer)) != -1) { 
baos.write(buffer, 0, count); 
} 
String filename = ze.getName(); 
byte[] bytes = baos.toByteArray(); 
// do something with 'filename' and 'bytes'... 
} 
} finally { 
zis.close(); 
}

代码示例

代码示例来源:origin: stackoverflow.com

is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));          
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) 
  filename = ze.getName();
  if (ze.isDirectory()) {
   File fmd = new File(path + filename);
   fmd.mkdirs();
  FileOutputStream fout = new FileOutputStream(path + filename);
  while ((count = zis.read(buffer)) != -1) 
    fout.write(buffer, 0, count);             
  fout.close();               
  zis.closeEntry();
zis.close();

代码示例来源:origin: apache/incubator-druid

final byte[] buffer = new byte[1 << 13];
progressable.progress();
try (ZipInputStream in = new ZipInputStream(fileSystem.open(zip, 1 << 13))) {
 for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
  final String fileName = entry.getName();
  final String outputPath = new File(outDir, fileName).getAbsolutePath();
  try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(outputPath))) {
   for (int len = in.read(buffer); len >= 0; len = in.read(buffer)) {
    progressable.progress();
    if (len == 0) {

代码示例来源:origin: spotbugs/spotbugs

private void getNextEntry() throws IOException {
  ze = zis.getNextEntry();
  if (ze == null) {
    zis.close();
  }
}

代码示例来源:origin: plantuml/plantuml

private InputStream getDataFromZip(InputStream is, String name) throws IOException {
  final ZipInputStream zis = new ZipInputStream(is);
  ZipEntry ze = zis.getNextEntry();
  while (ze != null) {
    final String fileName = ze.getName();
    if (ze.isDirectory()) {
    } else if (fileName.equals(name)) {
      return zis;
    }
    ze = zis.getNextEntry();
  }
  zis.closeEntry();
  zis.close();
  return null;
}

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

/**
 * @param zip Compressed file.
 */
public UnzipFileIO(File zip) throws IOException {
  zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
  ZipEntry entry = zis.getNextEntry();
  size = entry.getSize();
}

代码示例来源:origin: google/j2objc

try{
  ZipInputStream zip = new ZipInputStream(new FileInputStream(file));
  try {
    FileOutputStream fout = new FileOutputStream(tempFile, false);
    try{
     ZipOutputStream out = new ZipOutputStream(fout);
      while ((entry = zip.getNextEntry()) != null) {
        if (!entry.isDirectory()) {
             log("ignoring " + entry.toString());
        ZipEntry outEntry = new ZipEntry(entry.getName());
        outEntry.setMethod(entry.getMethod());
        outEntry.setComment(entry.getComment());
        out.write(bytes);
        out.closeEntry();
        zip.closeEntry();
     fout.close();    
    zip.close();

代码示例来源:origin: stackoverflow.com

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try { 
  byte data[] = new byte[BUFFER_SIZE];
      origin.close();
    f.mkdirs();
  ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
  try {
    ZipEntry ze = null;
    while ((ze = zin.getNextEntry()) != null) {
      String path = location + ze.getName();
      if (ze.isDirectory()) {
        File unzipFile = new File(path);
        if(!unzipFile.isDirectory()) {
        FileOutputStream fout = new FileOutputStream(path, false);
        try {
          for (int c = zin.read(); c != -1; c = zin.read()) {
            fout.write(c);
          zin.closeEntry();
    zin.close();

代码示例来源:origin: stackoverflow.com

List<String> classNames = new ArrayList<String>();
ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
  if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
    // This ZipEntry represents a class. Now, what class does it represent?
    String className = entry.getName().replace('/', '.'); // including ".class"
    classNames.add(className.substring(0, className.length() - ".class".length()));
  }
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

/**
 * Grab the rather voluminous vertical datum files from the OTP web server and save them in the NED cache directory.
 */
private void fetchDatum() throws Exception {
  LOG.info("Attempting to fetch datum files from OTP project web server...");
  URL datumUrl = new URL("http://dev.opentripplanner.org/resources/datum.zip");
  ZipInputStream zis = new ZipInputStream(datumUrl.openStream());
  /* Silly boilerplate because Java has no simple unzip-to-directory function. */
  for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
    if (entry.isDirectory()) {
      throw new RuntimeException("ZIP files containing directories are not supported");
    }
    File file = new File(cacheDirectory, entry.getName());
    if (!file.getParentFile().equals(cacheDirectory)) {
      throw new RuntimeException("ZIP files containing directories are not supported");
    }
    LOG.info("decompressing {}", file);
    OutputStream os = new FileOutputStream(file);
    ByteStreams.copy(zis, os);
    os.close();
  }
  zis.close();
  LOG.info("Done.");
}

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

try (FileInputStream fis = new FileInputStream(archive);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis)) {
  while ((entry = zis.getNextEntry()) != null) {
    if (entry.isDirectory()) {
      final File d = new File(extractTo, entry.getName());
      if (!d.getCanonicalPath().startsWith(destPath)) {
        final String msg = String.format(
      final File file = new File(extractTo, entry.getName());
      if (engine == null || engine.accept(file)) {
        if (!file.getCanonicalPath().startsWith(destPath)) {
          throw new ExtractionException(msg);
        try (FileOutputStream fos = new FileOutputStream(file)) {
          IOUtils.copy(zis, fos);
        } catch (FileNotFoundException ex) {

代码示例来源:origin: RaiMan/SikuliX2

return false;
String fpJar = uJar.getPath().split("!")[0];
if (!fpJar.endsWith(".jar")) {
 return false;
boolean shouldStop = false;
try {
 zJar = new ZipInputStream(new URL(fpJar).openStream());
 while ((zEntry = zJar.getNextEntry()) != null) {
  zPath = zEntry.getName();
  if (zPath.endsWith("/")) {
   continue;
    out.getParentFile().mkdirs();
   FileOutputStream aFileOS = new FileOutputStream(out);
   copy(zJar, aFileOS);
   aFileOS.close();
   if (nFiles > maxFiles) {
    break;
 zJar.close();
} catch (Exception ex) {
 log.error("doResourceListJar: %s", ex);

代码示例来源:origin: nutzam/nutz

public static ZipInputStream makeZipInputStream(String jarPath) throws MalformedURLException,
    IOException {
  ZipInputStream zis = null;
  try {
    zis = new ZipInputStream(new FileInputStream(jarPath));
  }
  catch (IOException e) {
    zis = new ZipInputStream(new URL(jarPath).openStream());
  }
  return zis;
}

代码示例来源:origin: confluentinc/ksql

try (ZipInputStream input = new ZipInputStream(new FileInputStream(sourceFile))) {
 while ((entry = input.getNextEntry()) != null) {
  if (entry.isDirectory()) {
   continue;
  final File file = new File(outputDir, entry.getName());
  final File parent = file.getParentFile();
  if (!parent.exists() && !parent.mkdirs()) {
  try (FileOutputStream output = new FileOutputStream(file)) {
   IOUtils.copy(input, output);
  } catch (final Exception e) {
   throw new RuntimeException("Error expanding entry '" + entry.getName() + "'", e);
 input.closeEntry();
} catch (final IOException e) {
 throw new KsqlException(

代码示例来源:origin: stackoverflow.com

OutputStream out = new FileOutputStream("your.file");
FileInputStream fin = new FileInputStream("your.zip");
BufferedInputStream bin = new BufferedInputStream(fin);
ZipInputStream zin = new ZipInputStream(bin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
  if (ze.getName().equals("your.file")) {
    byte[] buffer = new byte[8192];
    int len;
    while ((len = zin.read(buffer)) != -1) {
      out.write(buffer, 0, len);
    }
    out.close();
    break;
  }
}

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

try (FileInputStream fis = new FileInputStream(zip);
   ZipInputStream cin = new ZipInputStream(fis);
   FileOutputStream out = new FileOutputStream(newFile)) {
  cin.getNextEntry();
  IOUtils.copy(cin, out);
} finally {

代码示例来源:origin: stackoverflow.com

ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
  String name = entry.getName();
  boolean notInFiles = true;
  for (File f : files) {
    out.putNextEntry(new ZipEntry(name));
    while ((len = zin.read(buf)) > 0) {
      out.write(buf, 0, len);
  entry = zin.getNextEntry();
zin.close();
  InputStream in = new FileInputStream(files[i]);
  out.putNextEntry(new ZipEntry(files[i].getName()));

代码示例来源:origin: org.freemarker/freemarker

final URLConnection urlCon = jarBaseEntryUrl.openConnection();
if (!test_emulateNoJarURLConnections && urlCon instanceof JarURLConnection) {
  final JarURLConnection jarCon = (JarURLConnection) urlCon;
  final String jarBaseEntryUrlEF = jarBaseEntryUrl.toExternalForm();
  final int jarEntrySepIdx = jarBaseEntryUrlEF.indexOf(JAR_URL_ENTRY_PATH_START);
  if (jarEntrySepIdx == -1) {
      jarBaseEntryUrlEF.substring(jarEntrySepIdx + JAR_URL_ENTRY_PATH_START.length()), true);
  File rawJarContentAsFile = urlToFileOrNull(new URL(rawJarContentUrlEF));
  jarFile = rawJarContentAsFile != null ? new JarFile(rawJarContentAsFile) : null;
final InputStream in = new URL(rawJarContentUrlEF).openStream();
try {
  ZipInputStream zipIn = new ZipInputStream(in);
  try {
    while (true) {
      ZipEntry curEntry = zipIn.getNextEntry();
      if (curEntry == null) break;
      String curEntryPath = normalizeJarEntryPath(curEntry.getName(), false);
      if (curEntryPath.startsWith(baseEntryPath) && curEntryPath.endsWith(".tld")) {
        final String curEntryBaseRelativePath = curEntryPath.substring(baseEntryPath.length());
    zipIn.close();

代码示例来源:origin: termux/termux-app

try (ZipInputStream zipInput = new ZipInputStream(zipUrl.openStream())) {
  ZipEntry zipEntry;
  while ((zipEntry = zipInput.getNextEntry()) != null) {
    if (zipEntry.getName().equals("SYMLINKS.txt")) {
      BufferedReader symlinksReader = new BufferedReader(new InputStreamReader(zipInput));
      String line;
      String zipEntryName = zipEntry.getName();
      File targetFile = new File(STAGING_PREFIX_PATH, zipEntryName);
      boolean isDirectory = zipEntry.isDirectory();
        try (FileOutputStream outStream = new FileOutputStream(targetFile)) {
          int readBytes;
          while ((readBytes = zipInput.read(buffer)) != -1)
            outStream.write(buffer, 0, readBytes);

代码示例来源:origin: stackoverflow.com

ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
  InputStream in = new FileInputStream(files[i]);
  out.putNextEntry(new ZipEntry(files[i].getName()));
  for(int read = in.read(buffer); read > -1; read = in.read(buffer))
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry())
  for(int read = zin.read(buffer); read > -1; read = zin.read(buffer))

代码示例来源:origin: googleapis/google-cloud-java

private Path downloadEmulator() throws IOException {
 String[] splittedUrl = downloadUrl.toString().split("/");
 String fileName = splittedUrl[splittedUrl.length - 1];
 try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile))) {
  if (log.isLoggable(Level.FINE)) {
   log.fine("Unzipping emulator");
  ZipEntry entry = zipIn.getNextEntry();
  while (entry != null) {
   File filePath = new File(emulatorFolder, entry.getName());
   String canonicalEmulatorFolderPath = emulatorFolder.getCanonicalPath();
   String canonicalFilePath = filePath.getCanonicalPath();
   if (!canonicalFilePath.startsWith(canonicalEmulatorFolderPath + File.separator)) {
    throw new IllegalStateException(
      "Entry is outside of the target dir: " + entry.getName());
   if (!entry.isDirectory()) {
    extractFile(zipIn, filePath);
   } else {
    filePath.mkdir();
   zipIn.closeEntry();
   entry = zipIn.getNextEntry();

相关文章