在这种情况下,为什么必须以某种方式关闭ZipOutputStream? [英] Why do I have to close the ZipOutputStream in a certain way in this situation?

查看:58
本文介绍了在这种情况下,为什么必须以某种方式关闭ZipOutputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个例子:

示例1:

try (ByteArrayOutputStream baous = new ByteArrayOutputStream();     
    FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
        try (ZipOutputStream zous = new ZipOutputStream(baous)) {
            for (File file: files) {
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
                    zous.putNextEntry(zipEntry);
                    byte[] bytes = new byte[2048];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zous.write(bytes, 0, length);
                    }
                    zous.closeEntry();
                }
            }
        }
        baous.writeTo(fouscrx);
    } catch (FileNotFoundException ex) {} catch (IOException ex) {}

示例2:

try (ByteArrayOutputStream baous = new ByteArrayOutputStream();
          ZipOutputStream zous = new ZipOutputStream(baous);
       FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
            for (File file: files) {
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
                    zous.putNextEntry(zipEntry);
                    byte[] bytes = new byte[2048];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zous.write(bytes, 0, length);
                    }
                    zous.closeEntry();
                }
            }
            baous.writeTo(fouscrx);
        } catch (FileNotFoundException ex) {} catch (IOException ex) {}

第二示例无法正常工作.我的意思是文件内容不是空的,但是好像zip文件已损坏.

The second example doesn't work as I would like it to do. What I mean is that the file content is not empty but it' s as if the zip file was corrupted.

我希望您告诉我第一个示例为何不起作用.

推荐答案

ZipOutputStream

ZipOutputStream has to do several operations at the end of the stream to finish the zip file, so it's necessary for it to be closed properly. (Generally speaking, pretty much every stream should be closed properly, just as good practice.)

这篇关于在这种情况下,为什么必须以某种方式关闭ZipOutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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