java 下载压缩文件后打开报 不可预料的压缩文件末端

java 下载压缩文件后打开报 不可预料的压缩文件末端

如图所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lGIsmKva-1593490158214)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20200629165351623.png)]

背景:使用了ZipOutputStream将文件打包压缩成zip文件。使用了ByteArrayOutputStream将zip作为 文件流缓存到内存中。然后通过ByteArrayOutputStream的toByteArray()方法获取字节数组并base64编码方便接口调用。调用方解码获取字节数组再转换成对应文件。

原代码:

public static final String uploadFolder = "D:/booking/uploadFiles/";
//id为路径下要下载的文件名
public static Map downloadzip(String id) throws Exception {
        //完整路径
        String realpath = uploadFolder + id ;
        //文件流保存到字节数组缓存区
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(arrayOutputStream);
    //获取路径下所有的文件
        List<File> list = path(realpath);
    //压缩   
    try {
            for (File f:list) {
                byte[] buf = new byte[1024];
                zos.putNextEntry(new ZipEntry(f.getName()));
                int len;
                FileInputStream in = new FileInputStream(f);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } finally {
            byte[] bytes = arrayOutputStream.toByteArray();
            //base64编码
            String encode = new BASE64Encoder().encode(bytes);
            HashMap<String, String> map = new HashMap<>();
            map.put("base64str",encode);
            map.put("filename","attachment.zip");
            zos.close();
            return map;
        }
    
    public static   List<File> path(String filepath)  {
        ArrayList<File> list = new ArrayList<>();
        File file = new File(filepath);
        if (!file.isDirectory()) {

        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filepath + "/" + filelist[i]);
                if (!readfile.isDirectory()) {
                    list.add(readfile);
                } else if (readfile.isDirectory()) {
                    path(filepath + "/" + filelist[i]);
                }
            }
        }
        return list;
    }

修改后:

public static final String uploadFolder = "D:/booking/uploadFiles/";
//id为路径下要下载的文件名
public static Map downloadzip(String id) throws Exception {
        //完整路径
        String realpath = uploadFolder + id ;
        //文件流保存到字节数组缓存区
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(arrayOutputStream);
    //获取路径下所有的文件
        List<File> list = path(realpath);
    //压缩   
    try {
            for (File f:list) {
                byte[] buf = new byte[1024];
                zos.putNextEntry(new ZipEntry(f.getName()));
                int len;
                FileInputStream in = new FileInputStream(f);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } finally {
        //先关闭资源再获取字节码
        	zos.close();
            byte[] bytes = arrayOutputStream.toByteArray();
            //base64编码
            String encode = new BASE64Encoder().encode(bytes);
            HashMap<String, String> map = new HashMap<>();
            map.put("base64str",encode);
            map.put("filename","attachment.zip");
            return map;
        }
    
    public static   List<File> path(String filepath)  {
        ArrayList<File> list = new ArrayList<>();
        File file = new File(filepath);
        if (!file.isDirectory()) {

        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filepath + "/" + filelist[i]);
                if (!readfile.isDirectory()) {
                    list.add(readfile);
                } else if (readfile.isDirectory()) {
                    path(filepath + "/" + filelist[i]);
                }
            }
        }
        return list;
    }

调用代码:

@GetMapping("download/{id}")
    public void downLoad(@PathVariable("id") String id) throws Exception {
        Map map = UploadAndDownloadUtil.downloadzip("62bffdf76e894faaa75e061bd1b5c771");
        String filebase64 = (String) map.get("base64str");
        byte[] bytes = new BASE64Decoder().decodeBuffer(filebase64);
        FileOutputStream out = new FileOutputStream(new File("D:\\booking\\uploadFiles\\62bffdf76e894faaa75e061bd1b5c773\\fujian.zip"));
        out.write(bytes);
        out.close();
        System.out.println(JSON.toJSONString(map));
    }

差异是关闭ZipOutputStream流的顺序变了。在finally块中arrayOutputStream在执行toByteArray();之前要先关闭ZipOutputStream对象。然后就可以愉快的做下载功能 了。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值