加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java压缩文件三种方式介绍

(2015-11-02 17:04:57)
标签:

java

zip

分类: Java

通过java压缩文件方式一共有三种,在这里,给大家介绍一下(主要讲解java.util.zip方式实现的这种)

这三种方式分别是:

1、jdk自带的包java.util.zip.ZipOutputStream

2、org.apache.tools.zip.ZipOutputStream

3、org.apache.tools.ant.taskdefs.Zip

 

其中主要讲解第一种的代码构成:

 

比如需要某个路径下多个文件压缩为一个zip文件

代码如下:

// 把excel压缩到一个zip文件

public static void excelToZip(Map tmap) throws Exception {
   String files [] = new String[3];
   for(int i=0;i<3;i++){
    files[i]=path+i+".xls";
   }
   zipFiles(files,path+i+".zip");
 }
 //压缩方法
 public static boolean zipFiles(String[] files, String zipfile) throws Exception {
  boolean bf = true;
  File ff = new File(zipfile);
  if (!ff.exists()) {
   ff.createNewFile();
  }
  FileOutputStream out = new FileOutputStream(zipfile);
  ZipOutputStream zipOut = new ZipOutputStream(out);
  for (int i = 0; i < files.length; i++) {
   File f = new File(files[i]);
   if (!f.exists()) {
    bf = false;
   }
   try {
    FileInputStream in = new FileInputStream(files[i]);
    String fileName = files[i].substring(files[i].lastIndexOf('\\') + 1, files[i].length());
    ZipEntry entry = new ZipEntry(fileName);
    zipOut.putNextEntry(entry);
    int nNumber = 0;
    byte[] buffer = new byte[512];
    while ((nNumber = in.read(buffer)) != -1) {
     zipOut.write(buffer, 0, nNumber);
    }
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
    bf = false;
   }
  }
  zipOut.close();
  out.close();
  return bf;
 }
 // 测试主方法
 public static void  main(String args []) throws Exception {
  excelToZip();
 }

 

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有