简体   繁体   English

如何使用Java将文件从Zip文件读取到内存中?

[英]How can I read files from Zip file to memory with Java?

I found example from SUN site (http://java.sun.com/developer/technicalArticles/Programming/compression/), but it returns BufferedOutputStream. 我从SUN网站(http://java.sun.com/developer/technicalArticles/Programming/compression/)找到了示例,但它返回了BufferedOutputStream。 But I would like to get ZipEntry file as InputStream and then process next file. 但是我想将ZipEntry文件作为InputStream,然后处理下一个文件。 Is that possible? 那可能吗? My program has no access to harddisk, so it cannot even temporarily save files. 我的程序无法访问硬盘,因此它甚至无法临时保存文件。

import java.io.*;
import java.util.zip.*;

public class UnZip {
   final int BUFFER = 2048;
   public static void main (String argv[]) {
      try {
         BufferedOutputStream dest = null;
         FileInputStream fis = new 
       FileInputStream(argv[0]);
         ZipInputStream zis = new 
       ZipInputStream(new BufferedInputStream(fis));
         ZipEntry entry;
         while((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " +entry);
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new 
          FileOutputStream(entry.getName());
            dest = new 
              BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) 
              != -1) {
               dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
         }
         zis.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Well, just change the part that writes the file into something you want to do with the data. 好吧,只需将将文件写入文件的部分更改为您想要处理的数据即可。

while((entry = zis.getNextEntry()) != null) {
    System.out.println("Extracting: " + entry);
    int count;
    byte[] data = new byte[BUFFER];
    String filename = entry.getName();
    System.out.println("Filename: " + filename);
    while ((count = zis.read(data, 0, BUFFER)) != -1) {
       // Do whatever you want with the data variable
       System.out.println(data);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM