Reputation: 1011
I need to put 2 files in one zip archive using java. I use the following code and it works fine with one file. When I call the method with two files it doesn't throw any exception but I have broken file as a result
private File createZipFile(File[] files) throws IOException {
File zipFile = new File("D:\\zip.zip");
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
for (File file: files) {
BufferedInputStream bufferedInputStream = null;
byte data[] = new byte[1024];
FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath());
bufferedInputStream = new BufferedInputStream(fileInputStream, 1024);
ZipEntry entry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(entry);
int count;
while ((count = bufferedInputStream.read(data, 0, 1024)) != -1) {
zipOutputStream.write(data, 0, count);
}
bufferedInputStream.close();
fileInputStream.close();
}
zipOutputStream.close();
return zipFile;
}
Upvotes: 3
Views: 2570
Reputation: 3370
It looks like you are missing zipOutputStream.closeEntry()
at the end of your loop.
Upvotes: 4