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