The following example shows creating a ZIP file out of user given directory.
It iterates through all sub directories recursively and updates ZIP entries.
The method zipOut.putNextEntry() adds a new file entry to the ZIP file.
Remove the drive prefix before making an entry to build the ZIP file in proper format.
It handles both empty and non-empty directories. If a ZIP Entry name ends with "/"
then its treated as directory entry. So to create a directory in ZIP file suffix the entry name with "/".
Check the source of ZipEntry.
ZipEntry.java
public boolean isDirectory()
{
return this.name.endsWith("/");
}
try {
String [] filePaths = directory.list();
FileInputStream fileInput = null; byte [] buf = new byte[1024];
String entryName = null; int index = 0;
File child = null;
/**
* Add each file as ZIP entry
*/ for (int i = 0 ; i < filePaths.length; i++) {
child = new File(directory, filePaths[i]);
entryName = child.getAbsolutePath();
/**
* Remove the drive prefix,
*
* C:\NEW2\ABC to NEW2\ABC
* C:\NEW2\file_ops.txt to NEW2\file_ops.txt
* C:\NEW2\CCCC\AAA\IPC.LOG to NEW2\CCCC\AAA\IPC.LOG
*
* If we don't remove the prefix, a directory
* named C: is getting created in the ZIP file.
* To avoid this remove the directory prefix.
*/
index = entryName.indexOf(File.separator); if (index > 0) {
entryName = entryName.substring(index + 1);
}