栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

java zip 压缩工具类

Java 更新时间:发布时间: 百科书网 趣学号



java zip 压缩工具类

目录结构

  • 环境依赖
  • zip压缩工具类










环境依赖


    org.springframework.boot
    spring-boot-starter
    2.3.2.RELEASE



    com.alibaba
    fastjson
    1.2.75
    compile










工具类
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class ZipUtil {


    
    public static void toZip(List inputStreamList, List zipFileNames, OutputStream outputStream) throws IOException {
        if (inputStreamList.size() <= 0) {
            return;
        }
        if (zipFileNames.size() <= 0) {
            return;
        }
        // 设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(outputStream));
            zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
        } catch (Exception e) {
            return;
        }
        // 循环将文件写入压缩流
        DataOutputStream os = null;

        for (int i = 0; i < inputStreamList.size(); i++) {
            zipos.putNextEntry(new ZipEntry(StringUtils.isEmpty(zipFileNames.get(i)) ? "解压的数据" + i : zipFileNames.get(i)));
            os = new DataOutputStream(zipos);
            byte[] b = new byte[4 * 1024];
            int length = 0;
            while ((length = inputStreamList.get(i).read(b)) != -1) {
                os.write(b, 0, length);
            }
            inputStreamList.get(i).close();
            zipos.closeEntry();
        }

        // 关闭流
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
//    @SneakyThrows
    public static  List unZipForJsonToList(ZipInputStream zipInputStream, Class toClass) throws IOException, NullPointerException {
        if (toClass == null) {
            throw new NullPointerException("提取的对象不能为空!");
        }
        if (zipInputStream == null) {
            throw new NullPointerException("压缩流不能为空!");
        }

        List list = new ArrayList<>();
        Map zipFile = getZipFile(zipInputStream);

        //map 的entry遍历方法
        for (Map.Entry en : zipFile.entrySet()) {

//            System.out.println(en.getKey() + " ==》 " + en.getValue());
            T t = JSONObject.parseObject(en.getValue(), toClass);
            list.add(t);
        }
        if (list.size() <= 0) {
            throw new NullPointerException("zip 提取数据失败!");
        }
        return list;
    }

    
//    @SneakyThrows
    public static  Map unZipForJsonToMap(ZipInputStream zipInputStream, Class toClass) throws IOException, NullPointerException {
        if (toClass == null) {
            throw new NullPointerException("提取的对象不能为空!");
        }
        if (zipInputStream == null) {
            throw new NullPointerException("压缩流不能为空!");
        }

        Map zipFile = getZipFile(zipInputStream);
        Map returnMap = new ConcurrentHashMap<>();

        //map 的entry遍历方法
        for (Map.Entry en : zipFile.entrySet()) {
//            System.out.println(en.getKey() + " ==》 " + en.getValue());
            T t = JSONObject.parseObject(en.getValue(), toClass);
            returnMap.put(en.getKey(), t);
        }
        if (returnMap.size() <= 0) {
            throw new NullPointerException("zip 提取数据失败!");
        }
        return returnMap;
    }

    
    public static Map getZipFile(ZipInputStream srcZip) throws IOException {

        //读取一个目录
        ZipEntry nextEntry = null;
        // 压缩包内的文件数据【字符串形式】。
        Map stringMap = new ConcurrentHashMap<>();
        StringBuilder jsonString = new StringBuilder();
        //不为空,则进入循环。
        while ((nextEntry = srcZip.getNextEntry()) != null) {
            String name = nextEntry.getName();
//            System.out.println("name = " + name);

//            for (String fileName : fileNames) {
//                if (!StringUtils.isEmpty(name) && name.equalsIgnoreCase(fileName)) {
//                    System.out.println("压缩包中存在当前文件名:" + fileName);
//                    System.out.println();

            // 提取文件数据。
            try (
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream)
            ) {


                int n;
                byte[] bytes = new byte[4 * 1024];
//            byte[] bytes = new byte[1];
                while ((n = srcZip.read(bytes)) != -1) {
                    bufferedOutputStream.write(bytes, 0, n);
                    // 获取文件数据。
                    jsonString.append(new String(bytes, 0, n));
                    //                System.out.print(jsonString);
                }
                stringMap.put(name, jsonString.toString());
                jsonString = new StringBuilder();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //关闭当前文件。
                srcZip.closeEntry();
            }


//            System.out.println();
//            System.out.println("================================================================================");
//            System.out.println();
        }
        return stringMap;
    }


    //    public static void main(String[] args) throws IOException {
    private static void main(String[] args) throws IOException {

//        List routes = unZipForJson(
//                new ZipInputStream(new FileInputStream(new File("C:\\Users\\zhangsan\\Desktop\\测速.zip")))
//                , Route.class
//        );
//        System.out.println("============================ 转换的对象列表 ==========================");
//        routes.forEach(System.out::println);
//        System.out.println("===================================================================");
    }
}

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1071945.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号