这种 zip 方法有什么问题吗?

发布于 2024-12-18 13:48:50 字数 946 浏览 0 评论 0原文

我有一个方法可以压缩 5 个文件。它生成一个 zip 文件,没有错误,但我无法打开它来检查内容。我尝试通过电子邮件发送它,但 gmail 说它无法发送损坏的文件。尝试在 Windows 中使用 WinRAR 打开会出现错误:

存档格式未知或已损坏

这是方法:

private void zipTestFiles() throws FileNotFoundException, IOException
{
    File[] filenames = fileDir.listFiles(fileNameFilter(Constants.PAGE_MON_FILENAME_FILTER));

    byte[] buf = new byte[1024];

    String outFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separatorChar + Constants.PAGEMONITOR_ZIP;
    DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(outFilename)));

    for (int i=0; i<filenames.length; i++)
    {
        FileInputStream in = new FileInputStream(filenames[i]);

        int len;
        while ((len = in.read(buf)) > 0)
        {
            out.write(buf, 0, len);
        }

        in.close();
        }
    out.close();
}

I have a method which zips up 5 files. It produces a zip file without error, but I cannot open it to examine the contents. I tried emailing it and gmail said it cannot send corrupt files. Trying to open with WinRAR in Windows results in an error stating:

The archive is either in unknown format or damaged

This is the method:

private void zipTestFiles() throws FileNotFoundException, IOException
{
    File[] filenames = fileDir.listFiles(fileNameFilter(Constants.PAGE_MON_FILENAME_FILTER));

    byte[] buf = new byte[1024];

    String outFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separatorChar + Constants.PAGEMONITOR_ZIP;
    DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(outFilename)));

    for (int i=0; i<filenames.length; i++)
    {
        FileInputStream in = new FileInputStream(filenames[i]);

        int len;
        while ((len = in.read(buf)) > 0)
        {
            out.write(buf, 0, len);
        }

        in.close();
        }
    out.close();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不可一世的女人 2024-12-25 13:48:50

您应该使用 ZipOutputStream 而不是 DeflaterOutputStream。并且不要忘记创建条目。在编写实现之前,请阅读 ZipOutputStream 的 javadoc。

You should use ZipOutputStream instead of DeflaterOutputStream. And do not forget to create entries. Read javadoc of ZipOutputStream before writing the implementation.

酷到爆炸 2024-12-25 13:48:50

尝试使用 Java 中已经存在的 ZipOutputStream。 DeflaterOutputStream 仅使用 DEFLATE 方法进行压缩,但不会自动放入 ZIP 标头。

Try with ZipOutputStream which already exists in Java. DeflaterOutputStream only uses DEFLATE method to compress but doesn't put ZIP headers automatically.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文