I have two examples :
Example 1:
try (ByteArrayOutputStream baous = new ByteArrayOutputStream();
FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
try (ZipOutputStream zous = new ZipOutputStream(baous)) {
for (File file: files) {
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
zous.putNextEntry(zipEntry);
byte[] bytes = new byte[2048];
int length;
while ((length = fis.read(bytes)) >= 0) {
zous.write(bytes, 0, length);
}
zous.closeEntry();
}
}
}
baous.writeTo(fouscrx);
} catch (FileNotFoundException ex) {} catch (IOException ex) {}
Example 2:
try (ByteArrayOutputStream baous = new ByteArrayOutputStream();
ZipOutputStream zous = new ZipOutputStream(baous);
FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
for (File file: files) {
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
zous.putNextEntry(zipEntry);
byte[] bytes = new byte[2048];
int length;
while ((length = fis.read(bytes)) >= 0) {
zous.write(bytes, 0, length);
}
zous.closeEntry();
}
}
baous.writeTo(fouscrx);
} catch (FileNotFoundException ex) {} catch (IOException ex) {}
The second example doesn't work as I would like it to do. What I mean is that the file content is not empty but it' s as if the zip file was corrupted.
I would like you to tell me how come the first example does not work.
ZipOutputStream
has to do several operations at the end of the stream to finish the zip file, so it's necessary for it to be closed properly. (Generally speaking, pretty much every stream should be closed properly, just as good practice.)