java實現將多個文件打包成zip壓縮文件以及對壓縮文件的加密

如果僅僅需要對文件進行壓縮,方法比較簡單,因爲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();


發佈了43 篇原創文章 · 獲贊 22 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章