引言:
Java 7 引入了try-with-resources 语句,本文将详细介绍 try-with-resources 的工作原理,优点以及如何在日常编程中有效使用它。
1. try-with-resources 简介:
try-with-resources 是一种特殊的 try 语句,它确保在语句执行完毕后,每个资源会被自动关闭。这一特性主要用于那些实现了 java.lang.AutoCloseable 或 java.io.Closeable 接口的资源对象,这包括所有的I/O类如 InputStream、OutputStream、java.sql.Connection 等。
2. 传统 try-catch-finally 对比 try-with-resources
以下是一个未使用 try-with-resources 但使用传统 try-catch-finally 语句来确保资源关闭的例子:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("file.txt"));
String line;
while (


2285

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



