释放资源的方式

try-catch-finally

  • 无论try中的程序是正常执行还是异常执行,最后都一定会执行finally
public static void main(String[] args) {
        try {
            System.out.println(10 / 2);
            //return; 跳出方法的执行
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("====finally执行了一次====");
        }

        System.out.println(chu(10,2));
    }

    public static int chu(int a,int b){
        try {
            return  a / b;
        } catch (Exception e) {
            e.printStackTrace();
            return -1; //代表出现异常
        } finally {
        }
    }

释放资源的案例

public static void main(String[] args) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            System.out.println(10 / 0);
            //需求:复制照片
            //1.创建一个字节输入流管道与源文件接通
            is = new FileInputStream("D:\\pt\\123.jpg");
            //2.创建一个字节输出流管道与目标文件接通
            os = new FileOutputStream("C:\\hhh\\123.jpg");

            System.out.println(10 / 0);

            //3.创建一个字节数组,负责转移字节数据
            byte[] buffer = new byte[1024];
            //4.从字节输入流读取字节数据,写出去到字节输出流,读多少写出去多少
            int len;//记住每次读取了多少个字节
            while ((len = is.read(buffer)) != -1){
                os.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源操作
            try {
                if(is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(os != null) os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

try-with-resource

  • 该资源使用完毕后,会自动调用其close()方法,完成对资源的释放

try(定义资源1;定义资源2;.....) {

        可能出现异常的代码;

}catch() { }

 public static void main(String[] args)  {

        try (
                //1.创建一个字节输入流管道与源文件接通
                InputStream is = new FileInputStream("D:\\pt\\123.jpg");
                //2.创建一个字节输出流管道与目标文件接通
                OutputStream os = new FileOutputStream("C:\\hhh\\123.jpg");

                //注意:这里只能放置资源对象
                //什么是资源?资源都是实现AutoCloseable接口。资源都有一个close方法,并且资源放到这里后
                //用完之后,会被自动调用其close方法完成资源的释放操作
        ){

            System.out.println(10 / 0);

            //3.创建一个字节数组,负责转移字节数据
            byte[] buffer = new byte[1024];
            //4.从字节输入流读取字节数据,写出去到字节输出流,读多少写出去多少
            int len;//记住每次读取了多少个字节
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值