Reading from a ZipInputStream into a ByteArrayOutputStream

后端 未结 10 1537
旧时难觅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);
        }
    }
    

提交回复
热议问题