文件压缩成压缩包,解压压缩包

news2024/10/7 4:30:58

压缩文件操作的工具类,压缩文件调用zip方法

package com.citicsc.galaxy.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import java.nio.charset.*;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName Test13
 * @Description TODO
 * @Author houbing
 * @Date 2023/9/4 17:01
 */

@Slf4j
public class ZipUtils {

	
	public static File[] unzip(File zipFile) throws IOException {
		
		try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"))) {
			File dirFile = zipFile.getParentFile();
			  
			for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {  
			    ZipEntry entry = (ZipEntry) entries.nextElement();  
			    String zipEntryName = entry.getName();
			    String outPath = (dirFile.getPath() + File.separator + zipEntryName);
			    if (entry.isDirectory()) {
			    	new File(outPath).mkdirs();
			    } else {
			    	InputStream in = zip.getInputStream(entry);  
			    	  
				    FileOutputStream out = new FileOutputStream(outPath);  
				    byte[] buf1 = new byte[1024];  
				    int len;  
				    while ((len = in.read(buf1)) > 0) {  
				        out.write(buf1, 0, len);  
				    }  
				    in.close();  
				    out.close(); 
			    }
			}  
			return dirFile.listFiles();
		} finally {
			
		}
	}
	
	
	public static void zip(File zipFile, File... files) throws IOException {
		
        ZipOutputStream outputStream = null;
        try {
            outputStream = new ZipOutputStream(new FileOutputStream(zipFile));
            zipFile(outputStream, files);
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } finally {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("zip", ex);
            }
        }
	}
	
	private static void zipFile(ZipOutputStream output, File... files) throws IOException {
        FileInputStream input = null;
        try {
            for (File file : files) {
            	if (file == null) continue;
                // 压缩文件
                output.putNextEntry(new ZipEntry(file.getName()));
                input = new FileInputStream(file);
                int readLen = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
                    output.write(buffer, 0, readLen);
                }
            }
        } finally {
            // 关闭流
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                	log.error("zipFile", ex);
                }
            }
        }
    }
}

解压压缩包工具类

package com.citicsc.galaxy.liquidity.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Objects;

/**
 * @ClassName Test13
 * @Description TODO
 * @Author houbing
 * @Date 2023/9/4 17:01
 */

@Slf4j
public class UnZipUtils {
    static String[] compressedExtensions = { "zip", "rar", "tar", "gz" };

    public static boolean isZipFile(File file) {
        String extension = FilenameUtils.getExtension(file.getName());
        boolean isCompressed = false;
        for (String compressedExtension : compressedExtensions) {
            if (extension.equalsIgnoreCase(compressedExtension)) {
                isCompressed = true;
                break;
            }
        }
        return isCompressed;
    }
    public static InputStream unzipStream(InputStream inputStream) throws IOException {
        //Fail-Fast
        if (inputStream == null) {
            return null;
        }
        //1.Jdk原生Zip流,会因为问价字符集编码不匹配,报MALFORMED错(畸形的)
        //ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        //2.Apach-commons-compress的Zip流,兼容性更好
        ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(inputStream);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (zipInputStream.getNextEntry() != null) {
            int n;
            byte[] buff = new byte[1024];
            while ((n = zipInputStream.read(buff)) != -1) {
                bos.write(buff, 0, n);
            }
        }
        bos.flush();
        bos.close();
        return new ByteArrayInputStream(bos.toByteArray());
    }

    public static void unzipFile(String filePath, String targetPath) throws IOException {
        FileInputStream fileInputStream = null;
        ZipArchiveInputStream zipInputStream = null;
        FileOutputStream fouts = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            zipInputStream = new ZipArchiveInputStream(fileInputStream, "GBK", true);
            ArchiveEntry ze;
            byte[] ch = new byte[256];
            while ((ze = zipInputStream.getNextEntry()) != null) {
                String path = targetPath + File.separator + ze.getName();
                File zipFile = new File(path);
                File parentPath = new File(zipFile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zipFile.exists())
                        zipFile.mkdirs();
//                    zipInputStream.close();
                } else {
                    if (!parentPath.exists())
                        parentPath.mkdirs();

                    fouts = new FileOutputStream(zipFile);
                    int i;
                    while ((i = zipInputStream.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    fouts.close();
//                    zipInputStream.close();
                }
            }
        } catch (Exception e) {
            log.error("Extract Error:{}", e.getMessage(), e);
        } finally {
            if (fouts != null) {
                fouts.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (zipInputStream != null) {
                zipInputStream.close();
            }
        }
    }
}

做测试的实例:首先是压缩文件的测试

解压测试的实例

在解压工具类使用时,isZipFile()方法是判断是否是压缩包

unzipFile()解压的方法

String filePathDir = "D:\\Galaxy\\upload";

使用cn.hutool.core.util.ZipUtil包里面的方法进行解压

首先需要导入hutool的maven坐标

然后直接上代码

liquidityConfigProperties.getDefaultStoragePath() 为 D:/Galaxy

public void uploadFile(Date tradingDay, MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        String dir = liquidityConfigProperties.getDefaultStoragePath()
                + File.separator
                + DateUtils.formatStr(tradingDay) + "/upload/";
        File folder = new File(dir);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String zipFileStr =  dir + originalFilename;
        File zipFile = new File(zipFileStr);
        if (UnZipUtils.isZipFile(zipFile)) {
            FileUtils.copyInputStreamToFile(file.getInputStream(), zipFile);
            ZipUtil.unzip(zipFile, Charset.forName("GBK"));
        }else {
            throw new BizException("文件格式不正确");
        }
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1003225.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

重磅:百度李彦宏、中科院曾毅入选,《时代周刊》AI最有影响力100人!

2023年9月8日&#xff0c;《时代周刊》发布了“2023年AI领域最有影响力100人” 榜单。 榜单权威吗&#xff1f; 有必要介绍下《时代周刊》。 《Time》&#xff08;时代周刊&#xff09;,1923年创刊于纽约&#xff0c;是美国公认的最重要的新闻杂志之一。《时代周刊》以报道精彩…

mybatis 中BigDecimal中的0存为null的坑

问题点: 做mybatis的插入和修改操作时&#xff0c;java中类型为Bigdicemal时&#xff0c;且值为0时&#xff0c;存入到数据库中的值为null&#xff0c;而不是0&#xff0c;其它的非0值正常 部分代码如下: 有问题的属性 可以看到是 Begdecimal 类型,对应查出来的日志如下: 可以…

chrome控制台怎么看hover的样式

​ 1. 悬浮显示是通过css控制台的 点击styles下面的 &#xff1a;hov&#xff0c;然后选中hover就可以了 2.如果是js控制的 js 失去悬浮以后&#xff0c;浮层就会隐藏&#xff0c;这个时候选中hover是没用的。 那怎么保留悬浮的状态呢&#xff0c;直接右键&#xff0c;会弹…

【Python】从入门到上头— 多线程(9)

进程和线程的区别 详见【Java基础】多线程从入门到掌握第一节(一.多线程基础) 一. _thread模块和threading模块 Python的标准库提供了两个模块&#xff1a;_thread和threading&#xff0c;_thread是低级模块&#xff0c;threading是高级模块&#xff0c;对_thread进行了封装。…

菜单组件Menu

前面讲解了如果构建GUI界面&#xff0c;其实就是把一些GUI的组件&#xff0c;按照一定的布局放入到容器中展示就可以了。在实际开发中&#xff0c;除了主界面&#xff0c;还有一类比较重要的内容就是菜单相关组件&#xff0c;可以通过菜单相关组件很方便的使用特定的功能&#…

在历史长河中,这个震撼了我!

在一个人的一生中&#xff0c;很容易低估世界发生的变化。 科技能够用我们无法想象的方式改变世界&#xff0c;直到它们真的发生。 咱们回顾这个世界的技术史&#xff0c;有助于看清楚未来几年甚至几十年内可能发生的改变。 我们的祖辈在童年时代&#xff0c;很难想象出会有一个…

从9.10拼多多笔试第四题产生的01背包感悟

文章目录 题面基本的01背包问题本题变式 本文参考&#xff1a; 9.10拼多多笔试ak_牛客网 (nowcoder.com) 拼多多 秋招 2023.09.10 编程题目与题解 (xiaohongshu.com) 题面 拼多多9.10笔试的最后一题&#xff0c;是一道比较好的01背包变式问题&#xff0c;可以学习其解法加深对…

手搓消息队列【RabbitMQ版】

什么是消息队列&#xff1f; 阻塞队列&#xff08;Blocking Queue&#xff09;-> 生产者消费者模型 &#xff08;是在一个进程内&#xff09;所谓的消息队列&#xff0c;就是把阻塞队列这样的数据结构&#xff0c;单独提取成了一个程序&#xff0c;进行独立部署~ --------&…

工具教程【甜心转译】-双语字幕、中文语音生成(配音),打破信息差

甜心转译 &#xff08;主站&#xff09;是一款AI加持的音/视频生成双语字幕、中文语音的软件。帮助人们更容易的获取外语信息、不管是学习、还是娱乐&#xff0c;快人一步。 主要功能 字幕生成&#xff1a;只需几个简单的步骤&#xff0c;轻松生成字幕。字幕翻译&#xff1a;…

【校招VIP】java语言考点之异常

考点介绍&#xff1a; 导致程序的正常流程被中断的事件&#xff0c;叫做异常。异常是程序中的一些错误&#xff0c;但并不是所有的错误都是异常&#xff0c;并且错误有时候是可以避免的。异常发生的原因有很多&#xff0c;通常包含以下几大类: 1.用户输入了非法数据。2.要打开的…

【Python】爬虫基础

爬虫是一种模拟浏览器实现&#xff0c;用以抓取网站信息的程序或者脚本。常见的爬虫有三大类&#xff1a; 通用式爬虫&#xff1a;通用式爬虫用以爬取一整个网页的信息。 聚焦式爬虫&#xff1a;聚焦式爬虫可以在通用式爬虫爬取到的一整个网页的信息基础上只选取一部分所需的…

首家!亚信科技AntDB数据库完成中国信通院数据库迁移工具专项测试

近日&#xff0c;在中国信通院“可信数据库”数据库迁移工具专项测试中&#xff0c;湖南亚信安慧科技有限公司&#xff08;简称&#xff1a;亚信安慧科技&#xff09;数据库数据同步平台V2.1产品依据《数据库迁移工具能力要求》、结合亚信科技AntDB分布式关系型数据库产品&…

pinduoduo(商品详情)API接口

为了进行电商平台 的API开发&#xff0c;首先我们需要做下面几件事情。 1&#xff09;开发者注册一个账号 2&#xff09;然后为每个pinduoduo应用注册一个应用程序键&#xff08;App Key) 。 3&#xff09;下载pinduoduo API的SDK并掌握基本的API基础知识和调用 4&#xff…

冠达管理:etf怎样购买?

ETF是一种指数基金&#xff0c;与传统的自动办理型基金不同&#xff0c;相比之下&#xff0c;ETF是一种被动出资东西&#xff0c;因为它们的方针是跟从某个特定的指数&#xff0c;而不是企图在市场上打败其他出资者。ETF通常具有较低的办理费用、较高的流动性和灵敏的买卖方法&…

CANoe的工作模式之争:模拟总线的两种运行方式

我们在文章《CANoe中的工作模式之争:由一段简单的代码引出的问题》中,介绍了模拟总线模式下的三种工作方式: animated with factoras fast as possibleslave mode由于模拟总线模式不需要连接真实ECU,无需和真实ECU保持时间同步,那么就可以在模拟总线上加速或放缓程序的运行…

pytorch从0开始安装

文章目录 一. 安装anaconda1.安装pytorch前需要先安装anaonda&#xff0c;首先进入官网&#xff08;Anaconda | The Worlds Most Popular Data Science Platform&#xff09;进行安装相应的版本。2.接着按如图所示安装,遇到下面这个选项时&#xff0c;选择all users.3.选择自己…

如何与 PGA Tour Superstore 建立 EDI 连接?

PGA Tour Superstore 是一家专业的高尔夫用品卖场&#xff0c;以销售高品质高尔夫球具、装备和配件为主要经营范围。其使命是为高尔夫爱好者提供一站式购物体验&#xff0c;帮助他们在球场上取得更优越的成绩。多年来&#xff0c;PGA Tour Superstore 凭借其卓越的产品选择、专…

EFCore 基于Code First开发的配置

EFCore版本&#xff1a;7.0.10 Visual Studio版本&#xff1a;2022 1、首先新建一个项目(无论是.net framework还是.net core都可以)&#xff0c;在项目中添加EFCore的程序包&#xff1a; 2、新建一个文件夹Models&#xff0c;把表模型都放在这个文件夹里 3、新建表模型&…

Java笔记:线程池

一. 正确使用ThreadPoolExecutor创建线程池 1.1、基础知识 Executors创建线程池便捷方法列表&#xff1a;下面三个是使用ThreadPoolExecutor的构造方法创建的 方法名功能newFixedThreadPool(int nThreads)创建固定大小的线程池newSingleThreadExecutor()创建只有一个线程的线…

三维模型3DTile格式轻量化压缩模型变形浅析

三维模型3DTile格式轻量化压缩模型变形浅析 在对三维模型进行轻量化压缩处理的过程中&#xff0c;常常会出现模型变形的现象。这种变形现象多数源于模型压缩过程中信息丢失或误差累积等因素。以下将对此现象进行详细分析。 首先&#xff0c;我们需要了解三维模型轻量化压缩的…