git
https://gitee.com/my739168148/auto-close-try-with-resource.git
限制
try-with-resource是java7版本引入的。
java版本說明
Autocloseable
只要是java.lang.Autocloseable接口的實現類,那么都可以使用try-with-resource來自動關閉資源。
使用
JDK1.8開始的操作,使用try-with-resource來自動關閉資源
將打開資源的語句放在try里面。
java會自動調用close方法,我們無需再finally中處理資源的關閉了。
// JDK1.8開始的操作,使用try-with-resource來自動關閉資源
try (FileInputStream fis = new FileInputStream(databasePath);FileInputStream fis1 = new FileInputStream(databasePath)){}catch (Exception e){}
Autocloseable使用示例
public class MainActivity extends AppCompatActivity {private static String TAG = "JJWorld.MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);try (AutoCl1 autoCl1 = new AutoCl1()){
// autoCl1.show();autoCl1.show2();}catch (Exception e){Log.i(TAG,"e:" + e.getMessage());}}class AutoCl1 implements AutoCloseable{public void show(){Log.i(TAG,"show is call");}public void show2() throws Exception{Log.i(TAG,"show is call");throw new FileNotFoundException();}@Overridepublic void close() throws Exception {Log.i(TAG,"close is call");}}
}
# 快捷鍵
try-catch-finally快捷鍵,Ctrl + Alt + T