• java 打包zip压缩包


    1、主要包

    java.util.zip
    
    • 1

    2、过程

    2.1 类
    public class ZipOutputStream extends DeflaterOutputStream implements ZipConstants {
        /**
         * Creates a new ZIP output stream.
         *
         * 

    The UTF-8 {@link java.nio.charset.Charset charset} is used * to encode the entry names and comments. * * @param out the actual output stream */ public ZipOutputStream(OutputStream out) { this(out, StandardCharsets.UTF_8); } /** * Creates a new ZIP output stream. * * @param out the actual output stream * * @param charset the {@linkplain java.nio.charset.Charset charset} * to be used to encode the entry names and comments * * @since 1.7 */ public ZipOutputStream(OutputStream out, Charset charset) { super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); if (charset == null) throw new NullPointerException("charset is null"); this.zc = ZipCoder.get(charset); usesDefaultDeflater = true; } }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    2.2 创建实例
    String zipName = "a.zip";
    FileOutputStream zipOutputStream = new FileOutputStream(zipName);
    ZipOutputStream zos = new ZipOutputStream(zipOutputStream);
    
    • 1
    • 2
    • 3
    2.3 文件写入压缩包
    String fileName = "a01.xlsx";
    FileInputStream fileInputStream = new FileInputStream(fileName);
    // 压缩包的文件名(携带路径时压缩包路径一致)
    String innerName =new File(fileName).getName()
    zos.putNextEntry(new ZipEntry(innerName));
    int loc = 0;
    byte[] BYTES = new byte[2 * 1024];
    while ((loc=fileInputStream.read(BYTES)) != -1){
        zos.write(BYTES,0,loc);
    }
    fileInputStream.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    2.4 结束压缩
    zos.close();
    zipOutputStream.close();
    
    • 1
    • 2

    3、异常

    java.util.zip.ZipException:duplicate entry

    压缩文件同名异常,不能重写写入同一个文件(同路径用文件名)

    4、完整

    package com.nsn.spring.boot.common.utils.file;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipOutputStream;
    
    // 批量压缩文件
    public class PackageZips {
        
        public static PackageZips getPackageZips = new PackageZips();
    
        private Logger logger = LoggerFactory.getLogger(PackageZips.class);
    
        // 压缩文件相关输出流
        public static FileOutputStream zipOutputStream = null;
    
        // 压缩文件对象
        public static ZipOutputStream zos = null;
    
        // 缓存文件列表 避免存在同名文件
        public static List<String> cacheFile = new ArrayList<String>();
    
        // 长度
        public final static byte[] BYTES = new byte[2 * 1024];
        /**
         * 打包文件
         * @param fileList  文件列表
         * @param zipName   压缩包名
         * @param paths     路径列表(区分不同目录)
         * @return
         * @throws Exception
         */
        public static double packFiles(
            List<String> fileList, 
            String zipName,
            List<String> paths
        ) throws Exception {
            try {
                long start = System.currentTimeMillis();
                setZipObject(zipName);
    
                for (int i = 0; i < fileList.size(); i++) {
                    String file = fileList.get(i);
                    if(cacheFile.contains(file) ) continue;
                    cacheFile.add(file);
                    compress(file,paths.get(i) + File.separator + new File(file).getName());
                }
                long now = System.currentTimeMillis() - start;
                return now/1000;
            }catch (ZipException e) {
                e.printStackTrace();
                return 0;
            }catch (Exception e) {
                throw new Exception(e);
            }finally {
                zos.close();
                zipOutputStream.close();
            }
        }
        /**
         * 文件打包zip
         * @param fileList  文件列表
         * @param zipName   压缩文件名称
         * @return          时间
         * @throws Exception
         */
        public static double packFiles(List<String> fileList, String zipName) throws Exception {
            try {
                long start = System.currentTimeMillis();
                setZipObject(zipName);
                for (String file : fileList) {
                    if(cacheFile.contains(file) ) continue;
                    cacheFile.add(file);
                    compress(file);
                }
                long now = System.currentTimeMillis() - start;
                return now/1000;
            }catch (Exception e) {
                e.printStackTrace();
                return 0;
            }finally {
                zos.close();
                zipOutputStream.close();
            }
        }
    	// 创建zip对象
        public static  void setZipObject(String zipName) throws IOException {
            cacheFile = new ArrayList<String>();
            if(!checkFile(zipName)) {
                new File(zipName).createNewFile();
            }
            zipOutputStream = new FileOutputStream(zipName);
            zos = new ZipOutputStream(zipOutputStream);
        }
        /**
         * 压缩过程
         * @param fileName      文件名(路径)
         * @throws Exception
         */
        public static void compress(String fileName) throws Exception {
            compress(fileName,new File(fileName).getName());
        }
    
        /**
         * 压缩过程
         * @param fileName      文件名称
         * @param innerZipName  该文件压缩包内部结构
         * @throws Exception
         */
        public static void compress(String fileName,String innerZipName) throws Exception {
            Boolean aBoolean = checkFile(fileName);
            if(!aBoolean) {
                throw new Exception(fileName + " 文件不存在!");
            }
    
            FileInputStream fileInputStream = new FileInputStream(fileName);
            getPackageZips().logger.info(fileName + "\t" + innerZipName);
            zos.putNextEntry(new ZipEntry(innerZipName));
            int loc = 0;
            while ((loc=fileInputStream.read(BYTES)) != -1){
                zos.write(BYTES,0,loc);
            }
            fileInputStream.close();
        }
    	// 验证文件是否存在
        public static Boolean checkFile(String name){
            if(name.indexOf(".") < 0) {
                return false;
            }
            File file = new File(name);
            if(file.exists()){
                return true;
            }
            return false;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146

    5、测试

    class test() {
        public static void main(String[] args) {
            List<String> fs = new ArrayList<String>();
            String zn = "res.zip";
            try {
                fs.add("aa.xlsx");
                fs.add("aaaa.xlsx");
                fs.add("aa.csv");
                double v = PackageZips.packFiles(fs, zn);
                System.out.println(v);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    计算机网络——网络层知识点
    Mongodb 中,与索引相关的监控指标
    模块化---common.js
    Metasploit-模块介绍
    Unknown custom element: <el-image>无法使用该组件,升级element-ui版本后项目报错
    ESP8266
    javascript中依次输出元素并不断循环实现echarts柱图动画效果
    【pytorch】目标检测:新手也能彻底搞懂的YOLOv5详解
    linux磁盘操作、分区、挂载、配额、raid5
    Springboot与RestTemplate
  • 原文地址:https://blog.csdn.net/qq_44708990/article/details/133161034