java实现将多个文件打包成zip压缩文件以及对压缩文件的加密

来源:互联网 发布:mac下的数据库软件 编辑:程序博客网 时间:2024/05/01 11:40

如果仅仅需要对文件进行压缩,方法比较简单,因为java的util包中提供了相关的压缩方法.

首先,引入java.util.zip.ZipEntry,java.util.zip.ZipOutputStream包

然后加入以下代码:

String now = StringUtils.dateToString(new Date());
String path = request.getServletPath();
path = request.getRealPath(path);
path = path.substring(0,path.lastIndexOf("\\"))+"\\";
File zipFile = new File(path+"edm_expcsv\\"+"EDM_expcsv_"+now+".zip"); //压缩的文件名和地址 

ZipOutputStream out2 = new ZipOutputStream(new FileOutputStream(zipFile));//传入压缩文件路径,得到压缩流

 byte[] buffer = new byte[1024];
 File[] file1 = {new File(path+file),new File(path+file2)};
for(int x=0;x<file1.length;x++) {
 FileInputStream fis = new FileInputStream(file1[x]);
out2.putNextEntry(new ZipEntry(file1[x].getName()));//将要压缩的文件放入压缩流
  int len;
//读入需要下载的文件的内容,打包到zip文件
  while((len = fis.read(buffer))>0) {
 out2.write(buffer,0,len);
  }
 out2.closeEntry();
 fis.close();
}
out2.close();


如果是要对文件压缩并加密,则使用下面的方法,但是值支持单个文件压缩

先将ant.jar commons-io.jar EncryptZip.jar EncryptZip.jar winzip.1.1.0.jar

5文件放到lib包中
然后在头文件import中加入String,java.io.File,de.idyl.winzipaes.AesZipFileEncrypter,de.idyl.winzipaes.impl.AESEncrypterBC
然后加入代码
File file = newFile(s); //定义压缩文件的路径
File zipFile = new File(b + "\\demo.zip");//压缩的文件名和地址
AESEncrypterBC bc = new AESEncrypterBC();
AesZipFileEncrypter azfe = new AesZipFileEncrypter(zipFile, bc);
azfe.setEncoding("UTF-8"); // 编码格式是在这传进去的
azfe.add(file,"123.jpg", "123"); //1:要压缩的文件路径,2:为压缩的文件命名3:为密码
azfe.close();


0 0
原创粉丝点击