妖碧落

导航

try,finally自动关流

public class demon7_tryfinally {

    public static void main(String[] args) throws IOException {
        //demo1();
        try(
            FileInputStream fi2 = new FileInputStream("xxx.txt");
            FileOutputStream fo2 = new FileOutputStream("yyy.txt");
            MyClose mc = new MyClose();    //  自动关流的原因是实现了自动关闭Autocloseable接口
            )
        {
            int b ;
            while ((b = fi2.read())!= -1) {
                fo2.write(b);
            }
        }        
    }

    public static void demo1() throws FileNotFoundException, IOException {
        FileInputStream fi1 = null;
        FileOutputStream fo1 = null;    //  局部变量必须赋值
        try{
            fi1 = new FileInputStream("xxx.txt");
            fo1 = new FileOutputStream("yyy.txt");
            int b;
            while((b = fi1.read())!=-1){
                fo1.write(b);
            }  
        }
        finally {
            try{
                if (fi1 != null) {
                    fi1.close();    //  尽量能关一个就关一个, 节省资源
                }
            }finally{
                if (fo1 != null) {
                    fo1.close();
                }
            }
            
            
            
        }
    }

}

class MyClose implements AutoCloseable{
    public void close() {
        System.out.println("wo guan le ");
    }
}

 

posted on 2019-08-06 22:54  妖碧落  阅读(714)  评论(0编辑  收藏  举报