Вы забыли позвонить closeEntry (). И вы должны вызвать close () для ZipOutputStream перед baos.toByteArray ():
public static byte[] compressAll(String... files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
return baos.toByteArray();
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.closeEntry();
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
Для ByteArrayOutputStream вы должны закрыть ZipOutputStream перед извлечением байтового массива из ByteArrayOutputStream. Для FileOutputStream то же самое. Вы должны закрыть ZipOutputStream перед закрытием FileOutputStream. Обратите внимание, что методы закрытия ресурсов вызываются в порядке, обратном их созданию.
public static void compressAll(String... files) throws IOException {
try (FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
}