TryFinally

来源:互联网 发布:淘宝电脑卷转换手机卷 编辑:程序博客网 时间:2024/06/10 04:52
public class Demo7_TryFinally {

    public static void main(String[] args) throws IOException  {
        //demo1();
        try(
        FileInputStream  a =new FileInputStream("xxx.txt");
        FileOutputStream b =new FileOutputStream("yyy.txt");
        Myclose mc =new Myclose();
        ){
        int c ;
        while ((c=a.read()) !=-1) {
            b.write(c);
            
        }}
        
        
        
    }
//1.6版本之前的异常处理的标准格式
    public static void demo1() throws FileNotFoundException, IOException {
        FileInputStream a = null;
        FileOutputStream b =null;
        try{
        a =new FileInputStream("xxx.txt");
        b =new FileOutputStream("ccc.txt");
        int c;
        while ((c =a.read()) !=-1) {
            b.write(c);
            
            
        }
        }finally{
            try{if (a!=null){
                a.close();
            }                        //try finally 嵌套是能关一个是一个
            }finally{
                if (b!=null) {
                    b.close();
                }
            }
            
            
        }
    }

}

class Myclose implements AutoCloseable{
    
    public void close(){
        
        System.out.println("我关了");
    }
}

原创粉丝点击