欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件打包成zip

程序员文章站 2024-03-14 15:03:46
...

文章简介
利用jdk把多个文件打包

package com.kingpoint.abc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
    private static final int  BUFFER_SIZE = 2 * 1024;

    /**
     * 将多个文件打包生成ZIP文件
     * @param List<String> srcFiles  要打包文件的路径
     * @param OutputStream out   打包后输出路径(包括zip文件名)
     */

    public static void ZipFiles(List<String> srcFilesFullPath , OutputStream out) {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        List<File> srcFiles = new ArrayList<>();
        for(String fullPath : srcFilesFullPath){
            srcFiles.add(new File(fullPath));
        }

        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            //System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

执行以上工具类的部分代码:
String finalPath = downloadTempPath + STANDING_BOOK_ZIP_FILE + UUID.randomUUID().toString() + ".zip";
OutputStream out = new FileOutputStream(finalPath);
ZipUtil.ZipFiles(allDocFiles, out);
相关标签: 用jar实现技术