How to read file from ZIP using InputStream?

后端 未结 7 863
旧巷少年郎
旧巷少年郎 2020-11-29 09:11

I must get file content from ZIP archive (only one file, I know its name) using SFTP. The only thing I\'m having is ZIP\'s InputStream. Most examples show how g

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 09:42

    OP was close. Just need to read the bytes. The call to getNextEntry positions the stream at the beginning of the entry data (docs). If that's the entry we want (or the only entry), then the InputStream is in the right spot. All we need to do is read that entry's decompressed bytes.

    byte[] bytes = new byte[(int) entry.getSize()];
    int i = 0;
    while (i < bytes.length) {
        // .read doesn't always fill the buffer we give it.
        // Keep calling it until we get all the bytes for this entry.
        i += zipStream.read(bytes, i, bytes.length - i);
    }
    

    So if these bytes really are text, then we can decode those bytes to a String. I'm just assuming utf8 encoding.

    new String(bytes, "utf8")
    

    Side note: I personally use apache commons-io IOUtils to cut down on this kind of lower level stuff. The docs for ZipInputStream.read seem to imply that read will stop at the end of the current zip entry. If that is true, then reading the current textual entry is one line with IOUtils.

    String text = IOUtils.toString(zipStream)
    

提交回复
热议问题