Reading from a ZipInputStream into a ByteArrayOutputStream

后端 未结 10 1519
旧时难觅i
旧时难觅i 2021-02-05 08:14

I am trying to read a single file from a java.util.zip.ZipInputStream, and copy it into a java.io.ByteArrayOutputStream (so that I can then create a

相关标签:
10条回答
  • 2021-02-05 08:17

    You probably tried reading from a FileInputStream like this:

    ZipInputStream in = new ZipInputStream(new FileInputStream(...));

    This won’t work since a zip archive can contain multiple files and you need to specify which file to read.

    You could use java.util.zip.ZipFile and a library such as IOUtils from Apache Commons IO or ByteStreams from Guava that assist you in copying the stream.

    Example:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (ZipFile zipFile = new ZipFile("foo.zip")) {
        ZipEntry zipEntry = zipFile.getEntry("fileInTheZip.txt");
    
        try (InputStream in = zipFile.getInputStream(zipEntry)) {
            IOUtils.copy(in, out);
        }
    }
    
    0 讨论(0)
  • 2021-02-05 08:22

    It is unclear how you got the zipStream. It should work when you get it like this:

      zipStream = zipFile.getInputStream(zipEntry)
    
    0 讨论(0)
  • 2021-02-05 08:24

    I would call getNextEntry() on the ZipInputStream until it is at the entry you want (use ZipEntry.getName() etc.). Calling getNextEntry() will advance the "cursor" to the beginning of the entry that it returns. Then, use ZipEntry.getSize() to determine how many bytes you should read using zipInputStream.read().

    0 讨论(0)
  • 2021-02-05 08:26

    You're missing call

    ZipEntry entry = (ZipEntry) zipStream.getNextEntry();

    to position the first byte decompressed of the first entry.

     ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();
     int bytesRead;
     byte[] tempBuffer = new byte[8192*2];
     ZipEntry entry = (ZipEntry) zipStream.getNextEntry();
     try {
         while ( (bytesRead = zipStream.read(tempBuffer)) != -1 ){
            streamBuilder.write(tempBuffer, 0, bytesRead);
         }
     } catch (IOException e) {
          ...
     }
    
    0 讨论(0)
  • 2021-02-05 08:34

    I'd use IOUtils from the commons io project.

    IOUtils.copy(zipStream, byteArrayOutputStream);
    
    0 讨论(0)
  • 2021-02-05 08:34

    t is unclear how you got the zipStream. It should work when you get it like this:

      zipStream = zipFile.getInputStream(zipEntry)
    

    If you are obtaining the ZipInputStream from a ZipFile you can get one stream for the 3d party library, let it use it, and you obtain another input stream using the code before.

    Remember, an inputstream is a cursor. If you have the entire data (like a ZipFile) you can ask for N cursors over it.

    A diferent case is if you only have an "GZip" inputstream, only an zipped byte stream. In that case you ByteArrayOutputStream buffer makes all sense.

    0 讨论(0)
提交回复
热议问题