try-with-resources 中的一个坑,注意避让

本文讲述了在使用 try-with-resources 时遇到的一个问题,即在异常情况下,前端无法接收到错误信息。问题源于 try-with-resources 在异常发生时会提前关闭流,导致前端接收的响应为空。通过对比 try-catch 与 try-with-resources 的编译后代码,揭示了 try-with-resources 的关闭逻辑,并分析了其对异常处理的影响。最后,建议在使用 try-with-resources 时要留意异常时流的关闭情况。
摘要由CSDN通过智能技术生成

一个简单的下载文件的例子。

这里会出现什么情况呢

 @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) throws Exception {
        String resourcePath = "/java4ye.txt";
        URL resource = DemoApplication.class.getResource(resourcePath);
        String path = resource.getPath().replace("%20", " ");
        try( ServletOutputStream outputStream  = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(path)) {


            byte[] bytes = new byte[8192];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }

            String fileName = "java4ye.txt";
            //            response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
//            response.setContentType("application/octet-stream");
//            response.setHeader("Access-Control-Expose-Headers", "File-Name");
//            response.setHeader("File-Name", fileName);
   // 异常
            int i = 1/0;

            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值