Java 7 引入的 try-with-resources
语句是一种用于自动管理资源的简洁方式。任何实现了 AutoCloseable
接口的资源(如文件、网络连接等)都可以使用 try-with-resources
语句自动关闭,从而简化代码并减少资源泄露的风险。
try-with-resources
语句的基本用法
下面是一个使用 try-with-resources
语句读取文件的示例:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,BufferedReader
和 FileReader
都实现了 AutoCloseable
接口,因此可以在 try-with-resources
语句中使用。try-with-resources
语句会在 try
块执行完毕后自动关闭这些资源。
多个资源管理
try-with-resources
语句还可以同时管理多个资源,只需用分号分隔各个资源:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
FileWriter fw = new FileWriter("output.txt")
) {
String line;
while ((line = br.readLine()) != null) {
fw.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,BufferedReader
和 FileWriter
都会在 try
块执行完毕后自动关闭。
自定义资源类
您也可以创建自己的实现了 AutoCloseable
接口的资源类,以便使用 try-with-resources
自动管理资源:
public class MyResource implements AutoCloseable {
public MyResource() {
System.out.println("MyResource created");
}
public void doSomething() {
System.out.println("Doing something with MyResource");
}
@Override
public void close() {
System.out.println("MyResource closed");
}
public static void main(String[] args) {
try (MyResource resource = new MyResource()) {
resource.doSomething();
}
}
}
在这个示例中,MyResource
实现了 AutoCloseable
接口,并在 close
方法中定义了资源释放逻辑。使用 try-with-resources
语句时,close
方法会在 try
块执行完毕后自动调用。
总结
try-with-resources
语句是一个强大的特性,可以自动管理实现了 AutoCloseable
接口的资源,减少资源泄露风险并使代码更简洁。在实际开发中,应该优先考虑使用 try-with-resources
来管理资源。