I need to create a zip file by using Java. Library is not important, but zip4j seems to be a good one. In this zip file, only some of the files or subdirectories will be password protected. For example in the following zip file, only the files starting with "*" will be password protected:
foo.zip
foo1.txt
*secure
*secure1.txt
*secure2.txt
Is there any way to implement this scenario in Java?
Thanks in advance...
this mavne dependency:
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.1</version>
</dependency>
code:
ZipParameters parameters = new ZipParameters();
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
ZipFile zip = new ZipFile(destFile, PASSWORD.toCharArray());
zip.setCharset(InternalZipConstants.CHARSET_UTF_8);
for (File file : srcFiles) {
if (file.isFile()) {
zip.addFile(file, parameters);
} else {
zip.addFolder(file, parameters);
}
}
Anyway, I found it by using zip4j. Fwollowing snippets can be used for creating both password protected and non-password protected files.
For the files to be password protected:
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(password);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
And the files that are not password protected:
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.