如果僅僅需要對文件進行壓縮,方法比較簡單,因爲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();
如果是要對文件壓縮並加密,則使用下面的方法,但是值支持單個文件壓縮
5文件放到lib包中