java 文件压缩方法 zipUtil

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipUtil {

    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    /**
     * 生成zip文件
     *
     * @param zipfullPath   压缩后的zip文件全路径
     * @param fileFullPaths 压缩前的文件全路径数组
     */
    public static void createZip(String zipfullPath, String[] fileFullPaths, String[] fileNames) {
        InputStream inputStream = null;
        ZipOutputStream zip = null;
        try {
            File file = new File(zipfullPath);
            // 如果输出目标文件夹不存在,则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            zip = new ZipOutputStream(new FileOutputStream(zipfullPath));
            for (int i = 0; i < fileFullPaths.length; i++) {
                String fullPath = fileFullPaths[i];
                if (null == fullPath || ("").equals(fullPath)) {
                    continue;
                }
                //创建文件
                file = new File(fullPath);
                String fileName = fileNames[i];
                //读文件流
                inputStream = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[inputStream.available()];
                inputStream.read(buffer);
                inputStream.close();

                //将读取的文件输出到zip中
                zip.putNextEntry(new ZipEntry(fileName));
                zip.write(buffer);
                zip.closeEntry();
                logger.info("-------> {}文件压缩成功 <-------", fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(inputStream, null, zip);
        }
    }

    /**
     * 文件内容写入ZipOutputStream
     *
     * @param zipOutput
     * @param inputStream
     * @param fileName
     * @throws IOException
     */
    public static void writeToZipStream(final ZipOutputStream zipOutput, InputStream inputStream, String fileName)
            throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            ZipEntry entry = new ZipEntry(fileName);
            zipOutput.putNextEntry(entry);
            // 向压缩文件中输出数据
            int read = 0;
            byte[] buffer = new byte[4096];
            while ((read = bis.read(buffer)) != -1) {
                zipOutput.write(buffer, 0, read);
                zipOutput.flush();
            }
            zipOutput.closeEntry();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
    }


    /**
     * 下载生成的文件
     *
     * @param zipfullPath zip全路径
     * @param response
     */
    public static void downLoadFile(String zipfullPath, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //创建文件
            File file = new File(zipfullPath);
            String fileName = file.getName();
            //读文件流
            inputStream = new BufferedInputStream(new FileInputStream(file));
            //available() 在读写操作前先得知数据流里有多少个字节可以读取
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            //清空响应
            response.reset();
            response.setCharacterEncoding("UTF-8");
            //setContentType的作用是使客户端浏览器,区分不同种类的数据   ctet-stream二进制数据
            response.setContentType("application/octet-stream; charset=utf-8");
            // 信息头会告诉浏览器这个文件的名字和类型。
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO8859-1"));
            response.setHeader("Content-Length", "" + file.length());
            //写文件流
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(inputStream, outputStream, null);
        }
    }


    private static void closeAll(InputStream inputStream, OutputStream outputStream, ZipOutputStream zipOutputStream) {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值