I am using below java, but when it zips, it creates a directory and zips all contents inside that directory. For ex. if I have a folder named 'Directory' and I want to zip the content to a Zipped file, inside the zipped file it creates a folder testZip and have files inside that. I need all files inside the zipped file, not inside a parent directory. Please help. or suggest if there is any other way.
package folderZip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolder {
public ZipFolder() {
}
public static void main(String[] args) throws Exception {
ZipFolder obj = new ZipFolder();
obj.zipFolder("C:\\Drive\\temp\\testZip","C:\\Drive\\temp\\FolderZiper.zip");
}
public void zipFolder(String srcFolder,
String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
private void addFileToZip(String path, String srcFile,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
private void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName,
zip);
} else {
addFileToZip(path + "/" + folder.getName(),
srcFolder + "/" + fileName, zip);
}
}
}
}