How to read file from ZIP using InputStream?

后端 未结 7 823
旧巷少年郎
旧巷少年郎 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:52

    Here a more generic solution to process a zip inputstream with a BiConsumer. It's nearly the same solution that was used by haui

    private void readZip(InputStream is, BiConsumer<ZipEntry,InputStream> consumer) throws IOException {
        try (ZipInputStream zipFile = new ZipInputStream(is);) {
            ZipEntry entry;
            while((entry = zipFile.getNextEntry()) != null){
                consumer.accept(entry, new FilterInputStream(zipFile) {
                    @Override
                    public void close() throws IOException {
                        zipFile.closeEntry();
                    }
                });
            }
        }
    }
    

    You can use it by just calling

    readZip(<some inputstream>, (entry, is) -> {
        /* don't forget to close this stream after processing. */
        is.read() // ... <- to read each entry
    });
    
    0 讨论(0)
提交回复
热议问题