How to create a zip file and keep entries for directories?
Posted
by
NathanZ
on Stack Overflow
See other posts from Stack Overflow
or by NathanZ
Published on 2013-06-27T16:18:31Z
Indexed on
2013/06/27
16:21 UTC
Read the original article
Hit count: 198
I would like to create a zip archive from a folder and keep entries for (non-empty) directories.
In the code below, FileInputStream
throws a FileNotFoundException
when a directory is passed to AddToZip
. I have tried to put a condition around the actual writing of bytes but it makes the whole archive invalid. How can I add directory entries to the archive?
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(file); // Throws a FileNotFoundException when directory
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
© Stack Overflow or respective owner