try-with-resources
主要想讲的介玩意儿叫
try-with-resources
跟JDK版本有关
1、首先在JDK1.7之前,必须在finally块中手动关闭资源,否则会导致资源的泄露。
/**
* JDK 1.7之前
* 完整的进行try-catch形式捕获
* 必须在finally块中手动关闭资源
*
* @author gary
*/
@Slf4j
public class TryCatchDemo {
public static String download(String fileUrl) throws IOException {
try {
FileInputStream inputStream = new FileInputStream(fileUrl);
} catch (IOException e) {
log.error("IO异常",e);
} finally {
// 先判断是否为空,再关闭资源
if (inputStream != null)
inputStream.close();
}
return;
}
2、在JDK1.7,可把待捕获的流单独定义。
/**
* JDK 1.7
* 可把流单独的定义出来 再去捕获
*
* @author gary
*/
@Slf4j
public class TryCatchDemo {
public static String download(String fileUrl) throws IOException {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(fileUrl);
} catch (IOException e) {
log.error("IO异常",e);
} finally {
// 先判断是否为空,再关闭资源
if (inputStream != null)
inputStream.close();
}
return;
}
3、JDK1.8 数据流会在try执行完毕后自动关闭
try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。
/**
* JDK 1.8
* 数据流会在try执行完毕后自动关闭
*
* @author gary
*/
@Slf4j
public class TryCatchDemo {
public static String download(String fileUrl, HttpServletResponse response){
// 多个参数以分号隔开
try(inputStream = new FileInputStream(fileUrl);
OutputStream outputStream = response.getOutputStream()) {
outputStream.flush();
log.info("::SUCCESS::");
} catch (IOException e) {
log.error("IO异常",e);
}
return;
}