try-with-resources 实例
所属分类 java
浏览量 1354
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The try-with-resources statement is a try statement that declares one or more resources.
A resource is an object that must be closed after the program is finished with it.
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Any object that implements java.lang.AutoCloseable,
which includes all objects which implement java.io.Closeable, can be used as a resource.
public interface AutoCloseable {
void close() throws Exception;
}
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
使用 try-with-resources
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
使用 try finally
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
多个资源
try(FileInputStream input = new FileInputStream("file.txt"); BufferedInputStream bufferedInput = new BufferedInputStream(input))
{
int data = buffereInput.read();
while(data != -1){
System.out.println( (char) data);
data = bufferedInput.read();
}
}
创建顺序的逆序关闭
关闭顺序 BufferedInputStream FileInputStream
完整例子
public class TryResourceTest implements AutoCloseable{
private String name;
private boolean error = false;
public TryResourceTest(String name,boolean error){
this.name = name;
this.error = error;
}
public static void main(String[] args) throws Exception {
try(TryResourceTest test1 = new TryResourceTest("test1",false)){
test1.hello();
}
System.out.println("111");
// 抛出异常 也会自动关闭
try(TryResourceTest test2 = new TryResourceTest("test2",true)){
test2.hello();
}
// 这里不会运行
System.out.println("222");
}
public void hello(){
if(error){
throw new RuntimeException("error,name="+name);
}
System.out.println("hello,name="+name);
}
public void close() throws Exception{
System.out.println("close run,name="+name);
}
}
上一篇
下一篇
注解优缺点
如何做好一个程序员
JDBC最佳实践
安卓手机充电器输出说明
linux性能测试工具sysbench简单使用
top命令使用