用org.apache.tools.zip压缩/解压缩zip文件

2023-11-12

package org.coolyongzi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


public class ZipTools {
    public static final Logger logger = LogManager.getLogger(FileTools.class);
    public ZipTools()
    {
       
    }
    /*
     * @description:Compressed files or folders
     * @param compressedFilePath String,zipFileRootPath String,zipFileName String
     * @return boolean
     */
    public static boolean compressFloderChangeToZip(String compressedFilePath,String zipFileRootPath,String zipFileName)
    throws IOException
    {
        File compressedFile = new File(compressedFilePath);
        if("".equalsIgnoreCase(zipFileName))
        {
            zipFileName = StringTools.getShortFileNameFromFilePath(compressedFilePath);
        }
        if(!StringTools.conversionSpecialCharacters(zipFileRootPath).endsWith(File.separator))
        {
            zipFileRootPath = zipFileRootPath + File.separator;
        }
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileRootPath + zipFileName));
        String base ="";
        logger.debug("compress [" + compressedFilePath + "] start!");
        boolean result = ZipTools.compressFloderChangeToZip(compressedFile,zipOutputStream,base);
        logger.debug("compress [" + compressedFilePath + "] end!");
        zipOutputStream.close();
        return result;
       
    }
   
    private static  boolean compressFloderChangeToZip(File compressedFile,ZipOutputStream zipOutputStream,String base)
    throws IOException
    {
        FileInputStream fileInputStream = null;
       
        try{
            if(compressedFile.isDirectory())
            {
                File[] childrenCompressedFileList = compressedFile.listFiles();
                base = base.length() == 0 ? "" : base + File.separator;
                for (int i = 0; i < childrenCompressedFileList.length; i++) {
                    ZipTools.compressFloderChangeToZip(childrenCompressedFileList[i],
                    zipOutputStream,base+childrenCompressedFileList[i].getName());
                }
            }
            else
            {
                if("".equalsIgnoreCase(base))
                {
                    base = compressedFile.getName();
                }
                zipOutputStream.putNextEntry(new ZipEntry(base));
                fileInputStream = new FileInputStream(compressedFile);
                int b;
                while((b=fileInputStream.read())!=-1)
                {
                    zipOutputStream.write(b);
                }
                fileInputStream.close();
            }
            return true;
        }catch(Exception e)
        {
            e.getStackTrace();
            logger.error(e.getMessage());
            return false;
        }
    }
    /*
     * @param:zipFilePath String,releasePath String
     * @return void
     * @description:Decompress A File
     */
    @SuppressWarnings("unchecked")
    public static void decompressFile(String zipFilePath,String releasePath) throws IOException
    {
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration<ZipEntry> enumeration = zipFile.getEntries();
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        ZipEntry zipEntry = null;
        String zipEntryNameStr ="";
        String[] zipEntryNameArray = null;
        while (enumeration.hasMoreElements()) {
            zipEntry = enumeration.nextElement();
            zipEntryNameStr = zipEntry.getName();
            zipEntryNameArray = zipEntryNameStr.split("/");
            String path = releasePath;
            File root = new File(releasePath);
            if(!root.exists())
            {
                root.mkdir();
            }
            for (int i = 0; i < zipEntryNameArray.length; i++) {
                if(i<zipEntryNameArray.length-1)
                {
                    path = path + File.separator+zipEntryNameArray[i];       
                    new File(StringTools.conversionSpecialCharacters(path)).mkdir();
                }               
                else
                {
                    if(StringTools.conversionSpecialCharacters(zipEntryNameStr).endsWith(File.separator))
                    {
                        new File(releasePath + zipEntryNameStr).mkdir();
                    }
                    else
                    {
                        inputStream = zipFile.getInputStream(zipEntry);
                        fileOutputStream = new FileOutputStream(new File(
                                StringTools.conversionSpecialCharacters(releasePath + zipEntryNameStr)));   
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buf)) > 0)
                        {
                            fileOutputStream.write(buf, 0, len);
                        }
                        inputStream.close();
                        fileOutputStream.close();
                    }
                }
            }
        }
        zipFile.close();
    }
}





测试类

package org.coolyongzi.testcase;

import java.io.IOException;

import org.coolyongzi.ZipTools;

import junit.framework.TestCase;

public class ZipToolsTest extends TestCase {

    protected void setUp() throws Exception {
        super.setUp();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testCompressFloderChangeToZip(){
        try {
            ZipTools.compressFloderChangeToZip("f:/iDocumentBanner2.gif", "f:", "test.zip");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    public void testDecompressFile(){
        try {
            ZipTools.decompressFile("f:/java对解压Zip格式的文件.zip","f:/test/");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用org.apache.tools.zip压缩/解压缩zip文件 的相关文章

随机推荐

  • 解决vue项目中出现的console报错问题

    解决vue项目中出现的console报错问题 问题描述 在vue项目中 使用console log输出是总是会报错 使用如下 控制台报错如下 页面报错如下 vue项目中使用的版本如下 package json文件 产生原因 ESLint代码
  • C#中 ??、 ?、 ?: 、?.、?[ ]

    1 可空类型修饰符 引用类型可以使用空引用表示一个不存在的值 而值类型通常不能表示为空 例如 string str null 是正确的 int i null 编译器就会报错 为了使值类型也可为空 就可以使用可空类型 即用可空类型修饰符 来表
  • 缓存系列文章--8.热点key问题(mutex key)

    转载请注明出处哈 http carlosfu iteye com blog 2269678 一 引出热点key问题 我们通常使用 缓存 过期时间的策略来帮助我们加速接口的访问速度 减少了后端负载 同时保证功能的更新 一般情况下这种模式已经基
  • 2020-04-21

    实验2 3 1 求1到100的和 10分 本题要求编写程序 计算表达式 1 2 3 100 的值 输入格式 本题无输入 输出格式 按照以下格式输出 sum 累加和 代码 int main int i 0 int sum 0 for i 0
  • Numpy--布尔索引

    布尔索引 布尔索引是通过相同数组上的True还是False来进行提取的 提取的条件可以有多个 那么如果有多个 可以使用 来代表且 用来代表或 如果有多个条件 那么每个条件要使用圆括号括起来 布尔运算也是矢量的 比如以下代码 a1 np ar
  • IOS拉伸圆角图片

    UIImage buttonImageNormal UIImage imageNamed whiteButton png UIImage stretchableButtonImageNormal buttonImageNormal stre
  • String,StringBuffer,StringBuilder三者的异同?

    String StringBuffer StringBuilder三者的异同 String 不可变的字符序列 底层使用char 存储 StringBUffer 可变的字符序列 线程安全的 效率低 底层使用char 存储 StringBuil
  • 刀片服务器做虚拟机,刀片服务器Vmware虚拟化部署经验分享(初稿).docx

    HP C7000刀片服务器虚拟机部署经验分享 本文主要介绍一台新的 HP C7000 刀片服务器从上架加电到进行虚拟机部署的主要步骤 第一部分 为刀片系统配置远程管理 首先附 C7000刀片服务器各组件示意图一张 注意图中的 Insight
  • 华为云服务器免费用,CDN免费用,数据库免费用,免费免费,全场免费

    华为云免费专区 全场免费 自从华为云17年进军公有云市场以来 市场份额增长神速 20年华为云以高达259 6 的同比增长速度 已然稳定公有云市场前三的位置 但很多人依然没有试用过华为云的产品 即便性价比很高 也不敢贸然更换厂商 俗话说是骡子
  • 【ubuntu】Anaconda 安装+环境配置:pytorch1.5.0+torchvision0.6.0+cudatoolkit10.1

    1 正确安装anaconda 1 下载对应Anaconda版本 以Anaconda3 5 3 1 Linux x86 64 sh为例 Anaconda下载连接 2 命令安装 bash Anaconda3 5 3 1 Linux x86 64
  • C语言文件详解(超级详细,记得收藏~~~)

    什么是文件 磁盘上的文件是文件 在程序设计中 我们一般读的文件有两种 程序文件 和 数据文件 程序文件包括源程序文件 后缀为 c 目标文件 win下后缀为 obj 可执行文件 win下环境后缀为 exe 数据文件 文件的内容不一定是程序 而
  • java oauth2登录以及权限_OAuth2实现单点登录SSO

    1 前言 技术这东西吧 看别人写的好像很简单似的 到自己去写的时候就各种问题 一看就会 一做就错 网上关于实现SSO的文章一大堆 但是当你真的照着写的时候就会发现根本不是那么回事儿 简直让人抓狂 尤其是对于我这样的菜鸟 几经曲折 终于搞定了
  • WebSocket和HTTP的区别及原理

    HTTP协议 HTTP是单向的 客户端发送请求 服务器发送响应 举例来说 当客户端向服务器发送请求时 该请求以HTTP或HTTPS的形式发送 在接收到请求后 服务器会将响应发送给客户端 每个请求都与一个对应的响应相关联 在发送响应后客户端与
  • Jni基础

    1 JNI 的一般开发流程 1 1 定义好本地的 native 方法 package com darren ndk day13 import java util UUID public class Simple1 public static
  • 【转码方式】-Base64

    Base64 作用 在数据传输过程中 如果报文中存在英文字母以外的字符 就会出现乱码 如中文 图片 或者二进制报文 此时就可以通过Base64将不规则的数据流转化成Base64规定的64个可打印的字符 提高数据的可读性和可打印性 转码原理
  • c++实现合并两个无序数组并以从大到小的顺序排序

    今天做了一下途游游戏的线上笔试题 题目中有一个是合并两个无序数组并排序 从大到小 在这里写一下我的思路 如果有更简单思路的大神请给我留言 我首先想到的一个思路就是把A和B先放在同一个数组里 在随便用一个排序算法对新数组进行排序 这个方法时间
  • Shell脚本中2>&1、>、>>等符号到底是什么含义

    场景 在Linux Shell命令中 我们经常会遇到命令中类似这样的 gt 2 gt 1 符号 那么这些符号是什么含义 有什么用处呢 下面一起来看下 概念 在Linux shell中 0 1 2代表文件描述符 名称 代码 操作符 Java中
  • C++多种解法求最大回文子串

    题目 给定一字符串 求最长的回文子串 解法一 暴力法 循环查找字符串中的所有回文子串 时间复杂度O N3 第一遍循环 选取开始点 i 第二遍循环 选取结束位置 j 第三遍循环 判断 i j 是否为回文字符串 int palindromeA
  • Mysql服务器的外部连接

    目录 前言 Windows上的客户端连接工具有 Linux上连接其他虚拟机上的MySQL服务器 在Windows上通过Navicat连接虚拟机上的Mysql服务器 1 我们先下载好Navicat 2 当我们下载安装好Navicat后 打开它
  • 用org.apache.tools.zip压缩/解压缩zip文件

    package org coolyongzi import java io File import java io FileInputStream import java io FileOutputStream import java io