Java后端使用流的形式输出zip压缩包给前端出现不可预料的压缩文件末端的正确解决方法

1:使用360压缩包打开

2:使用winRAR打开后点击修复功能即可修复

3:代码问题()

首先判断你的流是否都成功关闭了,若有一个流未关闭都会导致标题所诉问题

都关闭后则要看流的关闭顺序

        // 以流的形式下载文件
        BufferedInputStream fis = null;
        BufferedOutputStream toClient = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            String name = file.getName();
            fis.read(buffer);
            // 清空response
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            name = URLUtil.encode(name,Charset.defaultCharset());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + name);
            response.setHeader("download-filename",name);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            toClient.write(buffer);
            toClient.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (fis != null) {
                    System.out.println("fis关闭了");
                    fis.close();
                }
                if (toClient != null) {
                    System.out.println("toClient关闭了");
                    toClient.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

可以看见fis在调用完read方法后,后面就不会在执行了,然后就说toClient流的执行,所以要先关闭fis,然后再关闭toClient,若先关闭toClient后关闭fis就会导致文件无法压缩的问题