views:

31

answers:

3

In a Java web application I am creating a zip file from various in-memory files (stored as byte[]).

Here's the key bit of code:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    for (//each member of a collection of objects) {

        PDFDocument pdfDocument = //generate PDF for this member of the collection;
        ZipEntry entry = new ZipEntry(pdfDocument.getFileName());
        entry.setSize(pdfDocument.getBody().length);
        zos.putNextEntry(entry);
        zos.write(pdfDocument.getBody());//pdfDocument.getBody() returns byte[]
        zos.closeEntry();
    }
    zos.close();

The problem: I'm sometimes getting a "ZipException: duplicate entry" when doing the "putNextEntry()" line.

The PDF files themselves will certainly be different, but they may have the same name ("PDF_File_for_John_Smith.pdf"). Is a name collision sufficient to cause this exception?

A: 

Yes -- you can use a directory structure inside your ZIP file if you need to hold multiple files with the same file name.

+2  A: 

You can't store 2 entries with the same same name in a zip archive(in the same folder), much like you can't have 2 files with the same name in the same folder in a filesystem.

nos
Note that this is actually a contradiction to ZIP file format's specification, however that specification is utterly dumb and shouldn't be followed :)
Esko
+1  A: 

I believe so. Zip was originally intended to archive a directory structure, so it expects filenames to be unique. You could add directories to keep your files separated (and provide extra information to differentiate them, if you want).

Curtis