Eche un vistazo a la librería Apache Commons Compress, le proporcionó la funcionalidad que necesita.
Por supuesto "erickson" está en lo cierto con su comentario a su pregunta. Necesitará el archivo conentet y no el objeto java.io.File
. En mi ejemplo, supongo que tiene un método byte[] getTheContentFormSomewhere(int fileNummer)
que devuelve el contenido del archivo (en memoria) para el archivoNummer-th. - Por supuesto, esta función es un diseño pobre, pero solo es para la ilustración.
Se debe trabajar un poco como esto:
void compress(final OutputStream out) {
ZipOutputStream zipOutputStream = new ZipOutputStream(out);
zipOutputStream.setLevel(ZipOutputStream.STORED);
for(int i = 0; i < 10; i++) {
//of course you need the file content of the i-th file
byte[] oneFileContent = getTheContentFormSomewhere(i);
addOneFileToZipArchive(zipOutputStream, "file"+i+"."txt", oneFileContent);
}
zipOutputStream.close();
}
void addOneFileToZipArchive(final ZipOutputStream zipStream,
String fileName,
byte[] content) {
ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
zipStream.putNextEntry(zipEntry);
zipStream.write(pdfBytes);
zipStream.closeEntry();
}
snipets de su controlador http:
HttpServletResponse response
...
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=\"compress.zip\"");
response.addHeader("Content-Transfer-Encoding", "binary");
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
compress(outputBuffer);
response.getOutputStream().write(outputBuffer.toByteArray());
response.getOutputStream().flush();
outputBuffer.close();
¿Qué quiere decir que es un 'java.io.File'? Un objeto 'File' es solo un objeto de dirección elegante; no tiene ningún contenido de archivo. ¿Dónde están tus datos? – erickson