java打包ZIP包,带密码

来源:互联网 发布:win7设置公用网络 编辑:程序博客网 时间:2024/05/23 19:19

一,JDK自带的ZIP操作接口(java.util.zip)并不支持密码功能,要解决ZIP打包问题,在网上找到了两种比较好办的方法,一种是用java调用DOS命令,使用winRAR打包压缩包,并设置密码。另一张方法是使用zip4j方法。

二,先说使用DOS调用winRAR打包

这个方法比较简单,但是可能实用性不高,需要服务器安装winRAR解压软件,代码如下:

/** * 打包文件(带密码) * @param tempOutPath 文件集路径 * @param outFileName 压缩包名称(含扩展名) * @param strPwd (压缩包密码) * @throws Exception */public static void doZipFiles(String tempOutPath, String outFileName, String strPwd) throws Exception {Process process = Runtime.getRuntime().exec("C:\\Program Files\\WinRAR\\WinRAR.exe a -ep "+tempOutPath+"\\"+outFileName + " " + tempOutPath + "*.* -p"+strPwd);process.waitFor();if(process.exitValue() != 0){throw new Exception("打包加密失败!");}}
根据服务器winRAR的安装路径,更改一下上边代码即可

三,再说一下zip4j打包的方法

首先需要去下载zip4j,官网地址:http://www.lingala.net/zip4j/

如果官网进不去,可以去我的CSDN这里下载:点击打开链接  http://download.csdn.net/detail/mr_ljq/5185924

下载完后,将jar包导入到工程中,然后就是如何使用这个开源项目了,下边是我自己弄的一段代码,很简单:


/** * 打包压缩包(带密码) * @param srcfile 文件集合 * @param dest带路径,带扩展名的压缩包名字 * @param password 压缩包密码 */
public static void doZipFilesWithPassword(File[] srcfile, String dest, String password) {if (srcfile == null || srcfile.length == 0) {return;}ZipParameters parameters = new ZipParameters();// 压缩方式parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);// 压缩级别parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);// 加密方式if (!LoanStringUtil.isEmpty(password)) {parameters.setEncryptFiles(true);parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);parameters.setPassword(password);}ArrayList<File> existFileList = new ArrayList<File>();for (int i = 0; i < srcfile.length; i++) {if (srcfile[i] != null) {existFileList.add(srcfile[i]);}}try {ZipFile zipFile = new ZipFile(dest);zipFile.addFiles(existFileList, parameters);} catch (ZipException e) {e.printStackTrace();}}
把做好的文件集合传递给srcfile,然后把打包后的zip包路径,包括文件名传给dest,就OK了。这个方法就是简单打包加密,zip4j还有很多功能

原创粉丝点击