温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中try-with-resources的使用场景以及实际应用

发布时间:2021-07-05 18:40:52 来源:亿速云 阅读:160 作者:chen 栏目:大数据

本篇内容主要讲解“java中try-with-resources的使用场景以及实际应用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java中try-with-resources的使用场景以及实际应用”吧!

1、开篇,实际try-with-resources使用如下:

/**
     * 将二进制文件读取出来
     *
     * @param filePath 文本绝对路径
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] getReaderToBinary(String filePath) throws FileNotFoundException, IOException {

        int bufferSize = 4096; // 设置缓冲区大小
        byte buffer[] = new byte[bufferSize]; // 缓冲区字节数组
        File sourceFile = new File(filePath);
        byte[] b = null;
        try(InputStream fis = new FileInputStream(sourceFile);
            BufferedInputStream bis = new BufferedInputStream(fis, bufferSize);
            ) {
            int len = bis.available();
            b = new byte[len];
            bis.read(b, 0, len);
        }

        return b;
    }

上述例子参考地址:

     * 作者:这个人太懒了
     * 来源:CSDN
     * 原文:https://blog.csdn.net/qq_35546153/article/details/83421506
     * 版权声明:本文为博主原创文章,转载请附上博文链接!

之前,采用try-catch-finally,则较为繁琐不直观,甚至偶尔会忘记将其关闭,如下:

	InputStream fis = null;
        BufferedInputStream bis = null;

        try{
            fis = new FileInputStream(sourceFile);
            bis = new BufferedInputStream(fis, bufferSize);

            int len = bis.available();
            b = new byte[len];
            bis.read(b, 0, len);
        }finally {
            if(fis != null){
                fis.close();
            }
            if(bis != null){
                bis.close();
            }
        }

2、使用场景

try-with-resources的用法就是,在try关键字的后面跟一个括号,把需要关闭的资源定义在括号内。在try块执行完之后会自动的释放掉资源。

但是必须注意,并不是所有的期望关闭的代码都可以放进其中,只有实现了java.lang.AutoCloseable接口的类,才可以被自动关闭。

eg:上述代码示例中的 InputStream,其定义如下:

public abstract class InputStream implements Closeable

Closeable,其定义如下(from jdk1.5版本):

/**
 * A {@code Closeable} is a source or destination of data that can be closed.
 * The close method is invoked to release resources that the object is
 * holding (such as open files).
 *
 * @since 1.5
 */
public interface Closeable extends AutoCloseable

说明:

  • 1、try-with-resource语法是自 JDK7 新增的。

  • 2、其只是一个语法糖:当你将上面代码反编译后会发现,其实对JVM虚拟机而言,它看到的依然是之前的try-catch-finally写法

3、实际使用

场景以 打开了外部资源 居多:

  • 文件

  • 数据库连接

  • 网络连接

若有自定义的需求:

public class CustomResource implements java.lang.AutoCloseable {

    @Override
    public void close() {
        System.out.printf("调用了[%s]的close方法\n", this.getClass().getName());
    }


    public static void main(String[] args) {
        try (CustomResource customResource = new CustomResource();){
            // do something
            System.out.println("do something");
            throw new RuntimeException("测试抛出未知异常");
        }
    }
}

控制台输出如下:

do something
Exception in thread "main" java.lang.RuntimeException: 测试抛出未知异常
	at com.xxx.main(CustomResource.java:22)
调用了[com.xxx.CustomResource]的close方法

说明:即使try块中抛出异常,也不影响resource的关闭

4、其他要点

注意:

public class CustomResource implements java.lang.AutoCloseable {

    public CustomResource(){
        throw new RuntimeException("构造器异常:"+ this.getClass().getName());
    }
    @Override
    public void close() {
        System.out.printf("调用了[%s]的close方法\n", this.getClass().getName());
        throw new RuntimeException("close方法异常:"+ this.getClass().getName());
    }



    public static void main(String[] args) {
        try (CustomResource customResource = new CustomResource();){
            // do something
            System.out.println("do something");
        } catch (Exception e){
            System.out.println("do catch");
            e.printStackTrace();
        }
    }
}

控制台输出如下:

do catch
java.lang.RuntimeException: 构造器异常:com.xxx.CustomResource
	at com.xxx.CustomResource.<init>(CustomResource.java:13)
	at com.xxx.CustomResource.main(CustomResource.java:24)

解释说明(参考地址:https://www.cnblogs.com/itZhy/p/7636615.html):

try-with-resource时,如果对外部资源的处理和对外部资源的关闭均遭遇了异常,“关闭异常”将被抑制,“处理异常”将被抛出,但“关闭异常”并没有丢失,而是存放在“处理异常”的被抑制的异常列表中。

到此,相信大家对“java中try-with-resources的使用场景以及实际应用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI