使用java创建多条目zip文件时出现问题

时间:2011-08-02 20:44:49

标签: java zip

任何人都知道这个代码创建包含许多条目的zip文件是错误的

    private File zipAttachments(List<File> licenses) throws IOException
    {
        byte[] buf = new byte[1024];
        File licenseZip = new File("license.zip");
        FileOutputStream fos = new FileOutputStream(licenseZip);
        ZipOutputStream zip = new ZipOutputStream(fos);
        for(File license:licenses)
        {
            ZipEntry zipEntry = new ZipEntry(license.getName());
            FileInputStream in = new FileInputStream(license);
            zip.putNextEntry(zipEntry);
            int len;
            while ((len = in.read(buf)) > 0)
            {
                zip.write(buf, 0, len);
            }
            zip.closeEntry();
            in.close();
        }
        zip.close();

        return licenseZip;
    }

并且堆栈是

java.util.zip.ZipException: ZIP file must have at least one entry
        at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:304)
        at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:146)
        at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:321)

但是我很确定许可证参数不是一个空列表,所以这并不意味着我正在创建zip条目吗?

1 个答案:

答案 0 :(得分:2)

我认为你错过了这个方法的第一行:

if (licenses.isEmpty())
    throw new IllegalArgumentException("licenses is empty");