• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java try()语句实现try-with-resources异常管理机制操作

java 搞代码 4年前 (2022-01-09) 26次浏览 已收录 0个评论
文章目录[隐藏]

Java try()语句实现try-with-resources异常管理机制

java7 新增特性,对于try语句块中使用到的资源,不再需要手动关闭,在语句块结束后,会自动关闭,类似于python的with..as的用法。

利用这个特性,需要实现AutoCloseable接口,只有一个close方法,实现关闭资源的操作。

public interface AutoCloseable{
    public void close() throws Exception;
}

所有的流,都实现了这个接口,可以在try()中进行实例化。自定义的类只要实现了这个接口,也可以使用这个特性。

不使用try-with-resources时,使用的资源要在finally中进行释放

package stream; 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; 
public class TestStream { 
    public static void main(String[] args) {
        File f = new File("d:/test.txt");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f); 
        } catch (IOException e) {
            e.printStackTrace();
   <span style="color:transparent">来1源gaodai#ma#com搞*代#码1网</span>     } finally {
            // 在finally 里关闭流
            if (null != fis)
                try { 
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        } 
    }
}

使用try-with-resources时

形式为try(),括号内可以包含多个语句。

package stream;  
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;  
public class TestStream {  
    public static void main(String[] args) {
        File f = new File("d:/lol.txt");
  
        //把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
        try (FileInputStream fis = new FileInputStream(f)) {
            byte[] all = new byte[(int) f.length()];
            fis.read(all);
            for (byte b : all) {
                System.out.println(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }
}

自定义AutoCloseable实现

在TestAutoCloseable的close方法中打印信息

package test; 
public class TestAutoCloseable implements AutoCloseable{
 public TestAutoCloseable() {
  System.out.println("class TestAutoCloceable");
 }
 public void close() {
  System.out.println("function close() executed");
 }
}

测试代码

package test; 
public class TestFeature { 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try(TestAutoCloseable testAutoCloseable = new TestAutoCloseable()){   
  }
 } 
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java try()语句实现try-with-resources异常管理机制操作
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址