将文件夹中的文件压缩到zip

import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; //dir2zip:文件夹路径,zipName:zip文件名 public void zipDir(String dir2zip, String zipName) throws Exception { try { //create a ZipOutputStream to zip the data to ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName)); //assuming that there is a directory named inFolder (If there //isn't create one) in the same directory as the one the code //runs from, //call the zipDir method String rootPath = dir2zip; zipDir(dir2zip, zos, rootPath); //close the stream zos.close(); } catch(Exception e) { logger.info("SM315-Exception in FileBean.zipDir() 115 "+e); throw e; } } public void zipDir(String dir2zip, ZipOutputStream zos, String rootPath) throws Exception { try { //create a new File object based on the directory we // have to zip File File zipDir = new File(dir2zip); //get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; //loop through dirList, and zip the files for(int i=0; i<dirList.length; i++) { File f = new File(zipDir, dirList[i]); if(f.isDirectory()) { //if the File object is a directory, call this //function again to add its content recursively String filePath = f.getPath(); zipDir(filePath, zos, rootPath); //loop again continue; } //if we reached here, the File object f was not // a directory //create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); //create a new zip entry ZipEntry anEntry = new ZipEntry(f.getPath().substring(rootPath.length()+1)); //place the zip entry in the ZipOutputStream object zos.putNextEntry(anEntry); //now write the content of the file to the ZipOutputStream while((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } //close the Stream fis.close(); } } catch(Exception e) { logger.info("SM315-Exception in FileBean.zipDir() 116 "+e); throw e; } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值