Java_基础—流的标准处理异常代码1.7版本

package com.soar.stream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.omg.Messaging.SyncScopeHelper;

public class Demo9_TryFinally {
    /*
     * 流的标准处理异常代码1.7版本
     * 不需要fis.close(); fos.close();关流
     * 会自动关闭
     * 原理
         ** 在try()中创建的流对象必须实现了AutoCloseable这个接口,如果实现了,在try后面的{}(读写代码)执行后就会自动调用,流对象的close方法将流关掉 
     */
    public static void main(String[] args) throws IOException {
        try(
        FileInputStream fis = new FileInputStream("xxx.txt");
        FileOutputStream fos = new FileOutputStream("yyy.txt");
        //MyClose mc = new MyClose();   
        //如果不实现AutoCloseable接口就会报错,在try()中写的类不具备自动关闭的功能
            MyClose mc = new MyClose();     
        ){
        int b;
        while((b = fis.read()) != -1){
            System.out.println(b);
        }
        }

    }
}
class MyClose implements AutoCloseable{     //只要实现了AutoCloseable接口,就会自动实现其方法
    public void close(){
        System.out.println("我关了");
    }
}
posted @ 2017-07-24 10:25  Soar_Sir  阅读(165)  评论(0编辑  收藏  举报