The following example shows creating a ZIP file with user given list of files.
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.
createZipFile(zipFilePath, filePaths);
System.out.println("Successfully created zip file.");
}
public static void createZipFile(String zipFilePath, String [] filePaths) {
try {
/**
* Create ZIP file
*/
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
FileInputStream fileInput = null; byte [] buf = new byte[1024];
String entryName = null; int index = 0;
/**
* Add each file as ZIP entry
*/ for (int i = 0 ; i < filePaths.length; i++) {
fileInput = new FileInputStream(filePaths[i]);
entryName = filePaths[i];
/**
* Remove the drive prefix,
*
* 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);