标签:高效 996 java content printStackTrace IOException fileOutputStream fileInputStream
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(); } } } }
标签:高效,996,java,content,printStackTrace,IOException,fileOutputStream,fileInputStream 来源: https://www.cnblogs.com/1446358788-qq/p/12952138.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。