高效 告别996,开启java高效编程之门 4-4TWR方式关闭流资源

1    重点:

1.1  TWR方式关闭物理资源

2    TWR方式关闭物理资源demo
package com.imooc.zhangxiaoxi.resource;

import org.junit.Test;

import java.io.*;

/**
 * FileCopyTestNew
 *
 * @author 魏豆豆
 * @date 2020/5/25
 */
public class FileCopyTestNew {

    /**
     * T-W-R 关闭流的方法(jdk7 自动关闭输入流/输出流,不需要我们手动关闭)
     *
     * 1    新建流
     * 2    流的读取/写入
     */
    @Test
    public void fileCopyTestNew(){
        String fileInputStreamUrl = "lib2/FileCopyTest.java";
        String fileOutputStreamUrl = "targetTest/target2.txt";

        //TWR  try-with-result
        try(
                FileInputStream fileInputStream = new FileInputStream(fileInputStreamUrl);
                FileOutputStream fileOutputStream = new FileOutputStream(fileOutputStreamUrl);
                ){
                int conent;
                while ((conent=fileInputStream.read())!=-1){
                    fileOutputStream.write(conent);
                }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/1446358788-qq/p/12963533.html