我们之前对流的操作是这样的,下面是我写的一个生成验证码的接口方法:
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掉
-
-