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掉

相关推荐
噗噗126 分钟前
企业微信侧边栏应用与前端 JS-SDK 的深度整合指南
前端·javascript·企业微信
骇客野人10 分钟前
IntelliJ IDEA 菜单中英对照
java·ide·intellij-idea
我命由我1234510 分钟前
Kotlin 面向对象 - 枚举排序
android·java·开发语言·java-ee·kotlin·android studio·android-studio
朝阳3913 分钟前
react19【实战】配置化路由登录鉴权完整方案
前端·javascript·react.js
ShuiShenHuoLe21 分钟前
vue如何实现国际化,它来了!
前端·javascript·vue.js
其美杰布-富贵-李23 分钟前
Vue Router 实战教程
前端·javascript·vue.js
NutShell Wang26 分钟前
拆解 GitHub gh-stack:堆叠 PR 工作流的设计取舍与工程实现
前端·git·开源·github·代码复审·开发者工具·vibe coding
名字还没想好☜30 分钟前
React 用 IntersectionObserver 实现图片懒加载与无限滚动:封装一个 useInView Hook
前端·javascript·vue.js·react.js·react
Sam_Deep_Thinking30 分钟前
用Java 17从0到1写一个mini版RPC,理解远程调用的本质
java·面试·rpc·程序员·系统架构
敲代码的嘎仔1 小时前
从零搭建微服务:Spring Cloud Alibaba 全家桶踩坑实录(Nacos + OpenFeign + Gateway + Sentinel)
java·spring boot·spring·spring cloud·微服务·gateway·sentinel