定義
JDK7之后,Java多了個新的語法:try-with-resources語句,
可以理解為是一個聲明一個或多個資源的 try語句(用分號隔開)涎跨,
一個資源作為一個對象,并且這個資源必須要在執(zhí)行完關(guān)閉的崭歧,
try-with-resources語句確保在語句執(zhí)行完畢后隅很,每個資源都被自動關(guān)閉 。
任何實現(xiàn)了** java.lang.AutoCloseable**的對象, 包括所有實現(xiàn)了 java.io.Closeable 的對象
, 都可以用作一個資源率碾。
我們根據(jù)定義來自己實現(xiàn)一個玩玩:
public class MyAutoClosable implements AutoCloseable {
public void doIt() {
System.out.println("MyAutoClosable doing it!");
}
@Override
public void close() throws Exception {
System.out.println("MyAutoClosable closed!");
}
public static void main(String[] args) {
try(MyAutoClosable myAutoClosable = new MyAutoClosable()){
myAutoClosable.doIt();
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸出.png
發(fā)現(xiàn)close方法被自動執(zhí)行了叔营,這個的好處在于,我們又可以變懶了所宰,不用再去關(guān)心連接調(diào)用完了是否關(guān)閉绒尊,文件讀寫完了是否關(guān)閉,專心的實現(xiàn)業(yè)務(wù)即可仔粥。
我們根據(jù)這個特性婴谱,來試下文件讀寫
先試試傳統(tǒng)寫法
public void readFile() throws FileNotFoundException {
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader("d:/input.txt");
br = new BufferedReader(fr);
String s = "";
while((s = br.readLine()) != null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
需要在最后finally中關(guān)閉讀文件流。
我們再試試try with resource寫法
public void readFile() throws FileNotFoundException {
try(
FileReader fr = new FileReader("d:/input.txt");
BufferedReader br = new BufferedReader(fr)
){
String s = "";
while((s = br.readLine()) != null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
代碼也整潔了一些
通過查看源碼可以發(fā)現(xiàn)
- public class FileReader extends InputStreamReader
- public class InputStreamReader extends Reader
- public abstract class Reader implements Readable, Closeable
- public class BufferedReader extends Reader
- public abstract class Reader implements Readable, Closeable
發(fā)現(xiàn)FileReader和BufferedReader最終都實現(xiàn)了Closeable接口躯泰,所以根據(jù)try with resource 定義谭羔,他們都是可以自動關(guān)閉的。