1 重点:
1.1 关闭输入流输出流顺序
1.2 demo对比,本节目的:展现传统关闭流方式的繁琐
1.3 demo对比自己错误,字节读取的时候用while循环
1.4 demo对比自己错误,输入流输出流的创建 fileInputStream = new FileInputStream("lib2/FileCopyTest.java");
2 demo对比
验证:新生成的文件打印
package com.imooc.zhangxiaoxi.resource; import org.junit.Test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * FileCopyTest * * @author 魏豆豆 * @date 2020/5/24 */ public class FileCopyTest { //标准做法 /** * demo * 1 创建输入流/输出流 * 2 文件写入 * 3 物理流资源关闭 */ @Test public void copyTestOriginal(){ //1 创建输入流/输出流 String fileInputStreamUrl = "lib2/FileCopyTest.java"; String fileOutputStreamUrl = "targetTest/target.txt"; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(fileInputStreamUrl); fileOutputStream = new FileOutputStream(fileOutputStreamUrl); //读取的字节信息 int content; //迭代,读取/写入字节 未到达文尾的部分读取后放到新的文件中 while ((content=fileInputStream.read())!=-1){ fileOutputStream.write(content); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //3 物理流资源关闭 if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } //自己做的错误的 /** * demo * 1 创建输入流/输出流 * 2 文件写入 * 3 物理流资源关闭 */ @Test public void copyTest(){ //1 创建输入流/输出流 FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; //2 文件写入 int content = 0; try { if((content=fileInputStream.read())!=-1){ fileOutputStream.write(content); content++; } } catch (IOException e) { e.printStackTrace(); } //3 物理流资源关闭 if(fileOutputStream!=null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(fileInputStream!=null){ try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }