I'm trying to send multiple files at onces in my Response body. My issue is that i was not able to concat multiples Array List into one that i'm later able to re seperate into multiple files.
This is my code (that is not working) :
List<PDDocument> documents = splitter.split(PDDocument.load(documentData));
ArrayList<byte[]> newDocuments = new ArrayList<>();
for (PDDocument doc : documents)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
doc.save(os);
newDocuments.add(os.toByteArray());
os.close();
}
t.sendResponseHeaders(200,newDocuments.toArray().length);;
OutputStream responseBody = t.getResponseBody();
responseBody.write(newDocuments.toArray());
responseBody.close();
So my question is :
How to send back multiple files into a single http reponse using java 11 http server ?
Thank you !
UPDATE :
After fixing my code with the help of Joni i'm facing another issue : The Zip that is generated is corrupted :
This is the code :
Splitter splitter = new Splitter();
List<PDDocument> documents = splitter.split(PDDocument.load(documentData));
t.sendResponseHeaders(200, 0);
t.getResponseHeaders().set("Content-Type", "application/zip");
OutputStream responseBody = t.getResponseBody();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
int counter = 1;
for (PDDocument doc : documents)
{
ZipEntry zipEntry = new ZipEntry("document" + counter);
zos.putNextEntry(zipEntry);
ByteArrayOutputStream docOs = new ByteArrayOutputStream();
doc.save(docOs);
docOs.close();
zos.write(docOs.toByteArray());
zos.closeEntry();
zos.finish();
zos.flush();
counter++;
}
zos.close();
baos.close();
responseBody.write(baos.toByteArray());
responseBody.flush();
responseBody.close();