博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java try with resources方式关闭资源
阅读量:1953 次
发布时间:2019-04-27

本文共 2267 字,大约阅读时间需要 7 分钟。

在我们使用资源时,一般资源使用完毕,都需要把资源关闭掉,在JDK7之前,我们一般都是使用try-catch-finally在finally中进行资源的关闭。
示例如下:
public static void test1(){        FileInputStream ins = null;        FileOutputStream out = null;        try {            ins = new FileInputStream(new File("G://aa.text"));            out = new FileOutputStream(new File("G://bb.text"));            //业务逻辑        }catch (FileNotFoundException ex){            ex.printStackTrace();        }finally {            //关闭资源            if(ins != null){                try {                    ins.close();                }catch (Exception insex){                    insex.printStackTrace();                }            }            if(out != null){                try {                    out.close();                }catch (Exception outex){                    outex.printStackTrace();                }            }        }    }
我们使用了输入流和输出流,在使用完后,需要手动去关闭。
在jdk7后,提供了一种新的方式:try-with-resources 方式来管理资源,在try中声明资源,当程序执行完后,会自动将声明的资源关闭掉,方式如下:
public static void test2(){        try(FileInputStream ins = new FileInputStream(new File("G:/aa.text"));            FileOutputStream out = new FileOutputStream(new File("G://bb.text"))){            //业务逻辑        }catch (FileNotFoundException fnex){            fnex.printStackTrace();        }catch (IOException ioex){            ioex.printStackTrace();        }    }

附:

资源一般是指:实现了Closeable接口或者AutoCloseable接口,这种资源使用完毕后都需要关闭。

package java.io;import java.io.IOException;/** * 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 {
/** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. * *

As noted in {@link AutoCloseable#close()}, cases where the * close may fail require careful attention. It is strongly advised * to relinquish the underlying resources and to internally * mark the {@code Closeable} as closed, prior to throwing * the {@code IOException}. * * @throws IOException if an I/O error occurs */ public void close() throws IOException;}

转载地址:http://oghif.baihongyu.com/

你可能感兴趣的文章
POJ-2299 Ultra-QuickSort(树状数组)(离散化)
查看>>
POJ-3107 Godfather & POJ-2378 Tree Cutting(树的重心)
查看>>
基于SSM的兼职论坛系统的设计与实现
查看>>
基于java的图书管理系统的设计与实现
查看>>
基于java的SSM框架理财管理系统的设计与实现
查看>>
基于java的ssm框架就业信息管理系统的设计
查看>>
基于java的ssm框架的旅游网站设计与实现
查看>>
基于java的SSM框架的流浪猫救助网站的设计与实现
查看>>
基于java的SSM框架的教务关系系统的设计与实现
查看>>
别再问我什么是A/B测试了!
查看>>
如何用同期群分析模型提升留存?(Tableau实战)
查看>>
爱了,吹爆这个高颜值的流程图工具!
查看>>
一个数据项目
查看>>
基于JAVA_JSP电子书下载系统
查看>>
基于java出租车计价器设计与实现
查看>>
基于java的B2C的网上拍卖系统
查看>>
十二时辰篇:这该死的 996
查看>>
2021最新 上海互联网公司排名
查看>>
字节vs快手!取消大小周之战
查看>>
送一个闲置显示器!
查看>>