JDK1.7新特性--自动关闭类

JDK在1.7之后出现了自动关闭类的功能,该功能的出现为各种关闭资源提供了相当大的帮助,这里我们谈一谈自动关闭类。
JDK1.7之后出现了一个重要的接口,以及改造了一个重要的方法结构:
1、AutoCloseable自动关闭接口
2、try(){}--catch{}--finally{}
相应的 一些资源也实现了该接口,如preparedStatement、Connection、InputStream、outputStream等等资源接口。

接口的实现类要重写close()方法,将要关闭的资源定义在try()中,这样当程序执行完毕之后,资源将会自动关闭。自定义类如果要进行自动关闭,只需要实现AutoCloseable接口重写close()方法即可,
同时也只有实现了AutoCloseable接口才能将,自定义类放入到try()块中,否则编译不能通过,举例说明
代码如下:
  1. <pre name= "code" class= "java"> class ReadTxt extends AutoClassable {
  2. @Override
  3. public void close() throws Exception {
  4. System.out.println( "ReadTxt close");
  5. }
  6. public String readTextValue(String path){
  7. StringBuffer sb = new StringBuffer();
  8. try(BufferedReader br = new BufferedReader( new FileReader(path))){
  9. int line;
  10. while((line = br.read())!=- 1){
  11. sb.append(br.readLine()+ "\n")
  12. }
  13. }
  14. return sb.toString();
  15. }
  16. }
  17. class MainTest {
  18. public static void main(String[] args) {
  19. try (ReadTxt rt = new ReadTxt()) {
  20. String line = rt.readTextValue( "G:\\学习文档\\test.txt");
  21. System.out.println(line);
  22. }
  23. }
  24. }

猜你喜欢

转载自blog.csdn.net/Aliloke/article/details/80977099