定義
JDK7之后,Java多了個(gè)新的語(yǔ)法:try-with-resources語(yǔ)句,
可以理解為是一個(gè)聲明一個(gè)或多個(gè)資源的 try語(yǔ)句(用分號(hào)隔開(kāi)),
一個(gè)資源作為一個(gè)對(duì)象,并且這個(gè)資源必須要在執(zhí)行完關(guān)閉的,
try-with-resources語(yǔ)句確保在語(yǔ)句執(zhí)行完畢后,每個(gè)資源都被自動(dòng)關(guān)閉 。
任何實(shí)現(xiàn)了** java.lang.AutoCloseable**的對(duì)象, 包括所有實(shí)現(xiàn)了 java.io.Closeable 的對(duì)象
, 都可以用作一個(gè)資源。
我們根據(jù)定義來(lái)自己實(shí)現(xiàn)一個(gè)玩玩:
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();
}
}
}
發(fā)現(xiàn)close方法被自動(dòng)執(zhí)行了,這個(gè)的好處在于,我們又可以變懶了,不用再去關(guān)心連接調(diào)用完了是否關(guān)閉,文件讀寫(xiě)完了是否關(guān)閉,專心的實(shí)現(xiàn)業(yè)務(wù)即可。
我們根據(jù)這個(gè)特性,來(lái)試下文件讀寫(xiě)
先試試傳統(tǒng)寫(xiě)法
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)閉讀文件流。
我們?cè)僭囋噒ry with resource寫(xiě)法
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();
}
}
代碼也整潔了一些
通過(guò)查看源碼可以發(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最終都實(shí)現(xiàn)了Closeable接口,所以根據(jù)try with resource 定義,他們都是可以自動(dòng)關(guān)閉的。