Java7新特性:try-with-resources写法

我们之前对流的操作是这样的,下面是我写的一个生成验证码的接口方法:

java 复制代码
    /**
     * 生成验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){


        String captchaText = captchaProducer.createText();
        log.info("验证码内容:{}",captchaText);

        //存储redis,配置过期时间 , jedis/lettuce
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);


        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("获取流出错:{}",e.getMessage());
        }


    }

但在jdk7我们可以将流的操作写为:

java 复制代码
try (ServletOutputStream outputStream = response.getOutputStream()){

    ImageIO.write(bufferedImage,"jpg",outputStream);
    outputStream.flush();

} catch (IOException e) {
    log.error("获取流出错:{}",e.getMessage());
}
  • 什么是try-with-resources

    • 资源的关闭很多⼈停留在旧的流程上,jdk7新特性就有, 但是很多⼈以为是jdk8的

    • 在try( ...)⾥声明的资源,会在try-catch代码块结束后⾃动关闭掉

    • 注意点

      • 实现了AutoCloseable接⼝的类,在try()⾥声明该类实例的时候,try结束后⾃动调⽤的 close⽅法,这个动作会早于finally⾥调⽤的⽅法

      • 不管是否出现异常,try()⾥的实例都会被调⽤close⽅法

      • try⾥⾯可以声明多个⾃动关闭的对象,越早声明的对象,会越晚被close掉

相关推荐
ai大模型-探索者12 小时前
Function Call与MCP(区别、联系与实战)
java·服务器·网络
小码哥_常12 小时前
前端图片压缩实战——我把网站图片体积砍了 70%
前端
略略略咯咯12 小时前
啊啊啊啊啊
java·服务器·数据库
张一凡9312 小时前
把“不要乱改”从提示词里拿出来,放进可校验的提案里
前端·后端·架构
木子欢儿12 小时前
Debian 13 + vsftpd 搭建FTP服务
linux·服务器·前端·网络·debian
leeguoo12 小时前
让 Claude Code / Codex 用上你已登录的 Chrome
前端·chrome·ai编程
SL_staff12 小时前
运维救火实战:钉钉API变更致薪资计算中断,如何用可视化逻辑引擎5分钟热修复
java·开源·全栈
猫猫.15313 小时前
HashTable、HashMap、ConcurrentHashMap 核心区别总结
java·开发语言·java-ee
天蒙蒙亮13 小时前
打安卓apk包+“应用商城”发布
前端·uni-app
Lank_M13 小时前
视频压到指定大小总超一截?码率控制的误差拆开看
前端