zoukankan      html  css  js  c++  java
  • 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 ");
        }
    }
    竹杖芒鞋轻胜马,一蓑烟雨任平生。 回首向来萧瑟处,也无风雨也无晴。
  • 相关阅读:
    [NOI2001]炮兵阵地
    POJ 2411 Mondriaan's Dream
    【模板】割点(割顶)
    [Noip2007]Core树网的核
    2018.09.09模拟总结
    2018.09.08模拟总结
    [USACO11JAN]Roads and Planes
    最优贸易
    [USACO08JAN]Telephone Lines
    Calabash(葫芦娃)
  • 原文地址:https://www.cnblogs.com/yaobiluo/p/11312422.html
Copyright © 2011-2022 走看看