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;
}
Java 1.7 引入了 try-with-resources 语句,解决了在 finally 块中手动关闭资源可能导致的资源泄露问题。在 JDK 1.7 之前,程序员需要在 finally 中显式关闭资源,例如 FileInputStream。从 JDK 1.7 开始,可以将资源声明在 try 子句中,系统会在执行完毕后自动关闭。到了 JDK 1.8,这一特性得到进一步增强,多个资源可以以分号隔开,并且在 try 块结束后会自动关闭,简化了代码并提高了安全性。
1172

被折叠的 条评论
为什么被折叠?



