zoukankan      html  css  js  c++  java
  • try-with-resource 关闭 io流

    1.在利用IO流的时候我们都需要关闭IO流, 比如  input.close(),一般是放在 finally 里面,但是如果多个类的话情况就会很复杂.

    static void copy2(String src, String dst)  {
            InputStream in = null;
            try {
                in = new FileInputStream(src);
                OutputStream out  = null;
                try {
                    //在打开InputStream后在打开OutputStream
                    out = new FileOutputStream(dst);
                    byte[] buf = new byte[1024];
                    int n;
                    while ((n = in.read(buf)) >= 0) {
                        out.write(buf, 0, n);
                    }
                    
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                    }
                }
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

    一个简单的文件拷贝工作会整的很复杂,如果在有别的io流的话就会更复杂,整个代码很难懂,而且 close()方法调用的时候也会抛出异常,所以内部也需要捕获一次异常.

    2.利用 try-with-resource

        static void copy(String src, String dst) throws Exception, IOException {
            try (InputStream in = new FileInputStream(src);
                 OutputStream out = new FileOutputStream(dst)){
                byte[] buf = new byte[1024];
                int n;
                while ((n = in.read(buf)) >= 0) {
                    out.write(buf, 0, n);
                }
            } finally {
            }
        }

    利用 try-with-resource ,我们直接在 try ( )中声明实现了AutoCloseable 的类,就可以在代码执行完以后自动执行 close()方法,整个代码也会简洁不少.

    如果有多个需要关闭的类, 直接在()中声明类然后利用分号隔开就可以.

  • 相关阅读:
    asp.net中常用提示对话框
    winForm 常用总结
    C#的IS和AS运算符区别
    转 七种武器——.NET工程师求职面试必杀技
    C#中bool与Boolean有什么区别?string和String区别?
    转 面向程序员的数据库访问性能优化法则
    转:回音消除技术
    转C#中using和new的用法
    转 C# 性能优化之斤斤计较篇
    转:三种运行Powershell代码的方法
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/12863198.html
Copyright © 2011-2022 走看看