I am able to create a zip file,my requirement is to protect it via password.For that I am using zip4j library.Please click on the further link for reference.[https://github.com/srikanth-lingala/zip4j]
Below is the code.
public static void packZip(File output, List<File> sources) throws IOException {
System.out.println("Packaging to " + output.getName());
ZipOutputStream zipOut = initializeZipOutputStream(output, "password".toCharArray());
for (File source : sources) {
if (source.isDirectory()) {
zipDir(zipOut, "", source);
} else {
zipFile(zipOut, "", source);
}
}
zipOut.flush();
zipOut.close();
System.out.println("Done");
}
private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException {
if (!file.canRead()) {
return;
}
ZipParameters zipParameters = new ZipParameters();
zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
zipParameters.setCompressionLevel(CompressionLevel.NORMAL);
zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
zipParameters.setFileNameInZip(buildPath(path,file.getName()));
zos.putNextEntry(zipParameters);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4092];
int byteCount = 0;
while ((byteCount = fis.read(buffer)) != -1) {
zos.write(buffer, 0, byteCount);
}
ZipFile zipFile = new ZipFile(file, "password".toCharArray());
zipFile.addFile(file, zipParameters);
//zipFile.createSplitZipFileFromFolder(file, zipParameters, true, 10485760);
fis.close();
zos.closeEntry();
}
private static ZipOutputStream initializeZipOutputStream(File outputZipFile, char[] password)
throws IOException {
FileOutputStream fos = new FileOutputStream(outputZipFile);
return new ZipOutputStream(fos, password);
}
private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException {
if (!dir.canRead()) {
return;
}
File[] files = dir.listFiles();
path = buildPath(path, dir.getName());
for (File source : files) {
if (source.isDirectory()) {
zipDir(zos, path, source);
} else {
zipFile(zos, path, source);
}
}
}
When I am using ZipFile class for password protection, I am not able to extract zip file, during extraction it changes from .zip to String format. If I am using ZipOutputStream class for password protection, there is no change in file format during extraction but it is not asking the password as expected. Any help is appreciated,thanks in advance.