try-with-resources 自动关闭流

package com.fdy.javacTest;

import java.io.*;

/**
 * @Description:
 * @author: fdy
 * @date: 2020/3/29 17:23
 */
public class TryWithResourcesDemo {
    // 一个简单的复制文件方法。
    public static void copy(String src, String dst) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(dst);
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        //copy("G:/student.xlsx","G:/new_student.xlsx");
        newCopy("G:/student.xlsx","G:/new_student.xlsx");
    }

    private static void newCopy(String src, String dst) {
        try (  InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dst)){
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

详细描述:https://www.cnblogs.com/youtang/p/11441959.html

posted @ 2020-03-29 21:10  自然的风和雨  阅读(815)  评论(0)    收藏  举报