多文件byte[]压缩zip


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//依赖的包
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class TestController {
    @RequestMapping("/zip")
    public void code( HttpServletResponse response) throws IOException {
        byte[] fileByte1 = readBytesFromFile("/Users/lgb/test1.txt");
        byte[] fileByte2 = readBytesFromFile("/Users/lgb/test2.txt");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //TODO 下面可以做循环压缩,这里只做演示
        
        //添加到zip
        //一定要加目录
        zip.putNextEntry(new ZipEntry("test" + File.separator + "test1.txt""));
        IOUtils.write(fileByte1, zip);
        zip.closeEntry();

        zip.putNextEntry(new ZipEntry("test" + File.separator + "test2.txt""));
        IOUtils.write(fileByte2, zip);
        zip.closeEntry();
            
        IOUtils.closeQuietly(zip);
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"你想要的名称.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        
        IOUtils.write(data, response.getOutputStream());
    }

 	/***
 	 * 文件转换为byte[]
 	 */
    private static byte[] readBytesFromFile(String filePath) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;
        try {
            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytesArray;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值