欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java工具類實(shí)現(xiàn)文件壓縮zip以及解壓縮功能

 更新時(shí)間:2024年02月19日 09:17:38   作者:哭著改bug  
這篇文章主要給大家介紹了關(guān)于java工具類實(shí)現(xiàn)文件壓縮zip以及解壓縮功能的相關(guān)資料,文中主要使用使用的是hutool工具類,Hutool是一個(gè)Java工具類庫(kù),由國(guó)內(nèi)的程序員loolly開(kāi)發(fā),目的是提供一些方便、快捷、實(shí)用的工具類和工具方法,需要的朋友可以參考下

對(duì)hutool工具類進(jìn)行的封裝

依賴

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.15</version>
            <scope>compile</scope>
        </dependency>

壓縮代碼

package com.myrc.web.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 自定義 (zip壓縮包/文件) 操作工具類
 *
 * @author gjq
 * @date 2023/2/16
 */
@Slf4j
@SuppressWarnings("all")
public class ZipFileUtils {

    /**
    * 
     * 生成Zip壓縮包 (注意是對(duì)hutool的二次封裝,所以必須要有hutool依賴)
     *
     * @param targetZipFile 要生成的目標(biāo)zip壓縮包
     * @param sourceFiles   壓縮包中包含的文件集合
     * @param dirWithFlag   是否將文件目錄一同打包進(jìn)去 (true:壓縮包中包含文件目錄,false:壓縮包中不包含目錄)
     * @author liukai
     */
    public static void generateZip(File targetZipFile, List<File> sourceFiles, boolean dirWithFlag) {
        if (CollUtil.isNotEmpty(sourceFiles)) {
            File[] fileArr = sourceFiles.toArray(new File[]{});
            ZipUtil.zip(targetZipFile, dirWithFlag, fileArr);
        }
    }

    /**
     * 下載ZIP壓縮包(會(huì)對(duì)下載后的壓縮包進(jìn)行刪除)
     *
     * @param file     zip壓縮包文件
     * @param response 響應(yīng)
     * @author liukai
     */
    public static void downloadZip(File file, HttpServletResponse response) {
        OutputStream toClient = null;
        try {
            // 以流的形式下載文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            toClient.write(buffer);
            toClient.flush();
        } catch (Exception e) {
            log.error("下載zip壓縮包過(guò)程發(fā)生異常:", e);
        } finally {
            if (toClient != null) {
                try {
                    toClient.close();
                } catch (IOException e) {
                    log.error("zip包下載關(guān)流失敗:", e);
                }
            }
            //刪除改臨時(shí)zip包(此zip包任何時(shí)候都不需要保留,因?yàn)樵次募S時(shí)可以再次進(jìn)行壓縮生成zip包)
            file.delete();
        }
    }

    /**
     * 任何單文件下載
     *
     * @param file     要下載的文件
     * @param response 響應(yīng)
     * @author liukai
     */
    public static void downloadAnyFile(File file, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            // 清空response
            response.reset();
            //防止文件名中文亂碼
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            //根據(jù)文件動(dòng)態(tài)setContentType
            response.setContentType(new MimetypesFileTypeMap().getContentType(file) + ";charset=UTF-8");
            outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = fileInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

FileUtil 工具類補(bǔ)齊

public class FileUtil {
  /**
     * 獲取指定文件夾下所有文件,不含文件夾里的文件
     *
     * @param dirFilePath 文件夾路徑
     * @return
     */
    public static List<File> getAllFile(String dirFilePath) {
        if (StrUtil.isBlank(dirFilePath))
            return null;
        return getAllFile(new File(dirFilePath));
    }

    /**
     * 獲取指定文件夾下所有文件,不含文件夾里的文件
     *
     * @param dirFile 文件夾
     * @return
     */
    public static List<File> getAllFile(File dirFile) {
        // 如果文件夾不存在或著不是文件夾,則返回 null
        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
            return null;

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0)
            return null;

        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件,直接添加到結(jié)果集合
            if (childFile.isFile()) {
                files.add(childFile);
            }
            //以下幾行代碼取消注釋后可以將所有子文件夾里的文件也獲取到列表里
//            else {
//                // 如果是文件夾,則將其內(nèi)部文件添加進(jìn)結(jié)果集合
//                List<File> cFiles = getAllFile(childFile);
//                if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
//                files.addAll(cFiles);
//            }
        }
        return files;
    }
} 

解壓縮

zipUtil是hutool包下的工具類

File unzip = ZipUtil.unzip(zipPath, StandardCharsets.UTF_8); 

使用:

//獲取該目錄下全部的文件
List<File> allFile = FileUtil.getAllFile(configPath);
//對(duì)目標(biāo)文件集 壓縮
ZipFileUtils.generateZip(new File(zipPath),allFile,true);

附:Java hutool 實(shí)現(xiàn)多個(gè)文件壓縮成壓縮包并下載至本地

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>xxx</version>
        </dependency>
List<ReqDocZip> reqDocZips = dealWithOutPutItems(retPageDocFiles);
String[] fileNames = reqDocZips.stream().map(ReqDocZip::getName).toArray(String[]::new);
for (ReqDocZip reqDocZip : reqDocZips) {
 if (reqDocZip.getName().equals(fileName)) {
 //導(dǎo)出同名文件會(huì)異常,拼接一個(gè)隨機(jī)字符串
 fileName =  UUID.randomUUID() + "-" + fileName;
 break;
 }
}
ByteArrayInputStream[] inputStreams = reqDocZips.stream().map(ReqDocZip::getInputStream).toArray(ByteArrayInputStream[]::new);
response.setContentType("application/zip");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("導(dǎo)出歸檔文檔", StandardCharsets.UTF_8.toString()) + ".zip");
ZipUtil.zip(response.getOutputStream(), fileNames, inputStreams);
@Getter
@Setter
public class ReqDocZip {
  private String name;
  private InputStream inputStream;
}

總結(jié) 

到此這篇關(guān)于java工具類實(shí)現(xiàn)文件壓縮zip以及解壓縮功能的文章就介紹到這了,更多相關(guān)java文件壓縮zip及解壓縮內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論