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

📅 发布时间:2026/7/9 16:45:40 👁️ 浏览次数:
Java7新特性:try-with-resources写法
我们之前对流的操作是这样的下面是我写的一个生成验证码的接口方法/** * 生成验证码 * 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我们可以将流的操作写为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掉