加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java创建ZIP压缩文件的方法

发布时间:2020-12-14 17:42:02 所属栏目:Java 来源:网络整理
导读:本篇章节讲解Java创建ZIP压缩文件的方法。供大家参考研究。具体如下: 这里注意:建议使用org.apache.tools.zip.*包下相关类,否则可能会出现中文乱码问题。 /** * 压缩文件夹 * @param sourceDIR 文件夹名称(包含路径) * @param targetZipFile 生

本篇章节讲解Java创建ZIP压缩文件的方法。分享给大家供大家参考。具体如下:

这里注意:建议使用org.apache.tools.zip.*包下相关类,否则可能会出现中文乱码问题。

/**
 * 压缩文件夹
 * @param sourceDIR 文件夹名称(包含路径)
 * @param targetZipFile 生成zip文件名
 * @author liuxiangwei
 */
public static void zipDIR(String sourceDIR,String targetZipFile) {
  try {
    FileOutputStream target = new FileOutputStream(targetZipFile);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(target));
    int BUFFER_SIZE = 1024;
    byte buff[] = new byte[BUFFER_SIZE];
    File dir = new File(sourceDIR);
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(sourceDIR+" is not a directory!");
    }
    File files[] = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
      FileInputStream fi = new FileInputStream(files[i]);
      BufferedInputStream origin = new BufferedInputStream(fi);
      ZipEntry entry = new ZipEntry(files[i].getName());
      out.putNextEntry(entry);
      int count;
      while ((count = origin.read(buff)) != -1) {
        out.write(buff,count);
      }
      origin.close();
    }
    out.close();
  } catch (IOException e) {
    throw new MsgException("");
  }
}

希望本文所述对大家的java程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读