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

本文介绍了两个Java工具类,一个是用于压缩文件的ZipUtils,使用了ZipOutputStream和ApacheCommonsCompress库;另一个是UnZipUtils,用于解压文件,支持多种压缩格式并处理字符集问题。
摘要由CSDN通过智能技术生成

压缩文件操作的工具类,压缩文件调用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("文件格式不正确");
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值