Hãy xem qua thư viện Apache Commons Compress, nó đã chứng minh chức năng bạn cần.
Tất nhiên "erickson" là đúng whit cam kết của mình đối với câu hỏi của bạn. Bạn sẽ cần tệp conentet chứ không phải đối tượng java.io.File
. Trong ví dụ của tôi, tôi giả định rằng bạn có một phương thức byte[] getTheContentFormSomewhere(int fileNummer)
trả về nội dung tệp (trong bộ nhớ) cho tệpNội dung thứ hai. - Tất nhiên chức năng này là thiết kế kém, nhưng nó chỉ dành cho ilustration.
Nó sẽ làm việc một chút như thế này:
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 của bộ điều khiển http của bạn:
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();
Ý anh là gì đó là một 'java.io.File'? Đối tượng 'File' chỉ là một đối tượng địa chỉ ưa thích; nó không mang bất kỳ nội dung tập tin nào. Dữ liệu của bạn ở đâu? – erickson