为什么ZipInputStream无法读取ZipOutputStream的输出? [英] Why ZipInputStream can't read the output of ZipOutputStream?

查看:295
本文介绍了为什么ZipInputStream无法读取ZipOutputStream的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持这个junit测试:

I'm stuck with this junit test:

public void test() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream( out );
    zipOut.putNextEntry( new ZipEntry( "file" ) );
    zipOut.write( (new byte[] { 0x01, 0x02, 0x03 }) );
    zipOut.closeEntry();
    zipOut.close();

    ZipInputStream zipIn = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
    ZipEntry entry = zipIn.getNextEntry();
    assertNotNull( entry );
    assertEquals( "file", entry.getName() );
    assertEquals( 3, entry.getSize() );
}

我正在编写一个名为file且内容为ZipOutputStream的三个字节。然后我尝试用ZipInputStream读取创建的数据,但最后一个断言失败,因为 entry.getSize() -1 而不是 3

I'm writing a file with the name "file" and a content of three bytes to a ZipOutputStream. Then I try to read the created data with a ZipInputStream, but the last assert fails, because entry.getSize() is -1 and not 3, as expected.

我在这里做错了什么?我需要更改什么来恢复文件的内容?我想,我首先要知道能够从流中读取数据的长度吗?

What am I doing wrong here? What do I have to change to restore the content of "file"? I think, I first have to know the length to be able to read the data from the stream?

推荐答案

你实际上必须要读取条目的内容,然后 entry.getSize()将返回正确的大小。

You actually have to read the contents of the entry, then entry.getSize() will return the correct size.

阅读条目使用:

    byte[] buf = new byte[1024];
    int len;
    while ((len = zipIn.read(buf)) > 0) {
        // use data;
    }

这篇关于为什么ZipInputStream无法读取ZipOutputStream的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆