加入收藏 | 设为首页 | 会员中心 | 我要投稿 我爱制作网_潮州站长网 (http://www.0768zz.com/)- 物联安全、建站、操作系统、云计算、数据迁移!
当前位置: 首页 > 教程 > 正文

Java的IO操作中关闭流的谨慎点

发布时间:2021-12-11 15:23:40 所属栏目:教程 来源:互联网
导读:一、错误示例1 public void CopyFile() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader(c:xy1.txt); // ① fw = new FileWriter(c:xy2.txt); // ② char[] charBuffer = new char[1024]; int len = 0; while ((len = fr.read

一、错误示例1
 public void CopyFile()
 {
 FileReader fr = null;
 FileWriter fw = null;
 try
 {
 fr = new FileReader("c:xy1.txt"); // ①
 fw = new FileWriter("c:xy2.txt"); // ②
 char[] charBuffer = new char[1024];
 int len = 0;
 while ((len = fr.read(charBuffer)) != -1)
 {
 fw.write(charBuffer, 0, len);
 }
 System.out.println("文件复制成功");
 }
 catch (IOException e)
 {
 throw new RuntimeException("文件拷贝操作失败");
 }
 finally
 {
 try
 {
 fr.close(); // ③
 fw.close(); // ④
 }
 catch (IOException e)
 {
 throw new RuntimeException("关闭失败");
 }
 }
 }
 若①中代码出错,fr根本就没有初始化,执行③的时候就会报空指针异常。②④同样是这个道理。
 
Java中获取文件大小的正确方法 http://www.linuxidc.com/Linux/2014-04/99855.htm
 
Java自定义类开实现四舍五入 http://www.linuxidc.com/Linux/2014-03/98849.htm
 
Java多线程:一道阿里面试题的分析与应对 http://www.linuxidc.com/Linux/2014-03/98715.htm
 
 
二、错误示例2
 public void CopyFile()
 {
 FileReader fr = null;
 FileWriter fw = null;
 try
 {
 fr = new FileReader("c:xy1.txt"); // ①
 fw = new FileWriter("c:xy2.txt"); // ②
 char[] charBuffer = new char[1024];
 int len = 0;
 while ((len = fr.read(charBuffer)) != -1)
 {
 fw.write(charBuffer, 0, len);
 }
 System.out.println("文件复制成功");
 }
 catch (IOException e)
 {
 throw new RuntimeException("文件拷贝操作失败");
 }
 finally
 {
 try
 {
 if (null != fr)
 {
 fr.close(); // ③
 }
 if (null != fw)
 {
 fw.close(); // ④
 }
 }
 catch (IOException e)
 {
 throw new RuntimeException("关闭失败"); // ⑤
 }
 }
 }
 加上是否为空的判断可以避免空指针异常。但是如果③执行出错,程序会直接进入⑤而④根本没有得到执行,导致无法关闭。
 
三、正确示例
 public void CopyFile()
 {
 FileReader fr = null;
 FileWriter fw = null;
 try
 {
 fr = new FileReader("c:xy1.txt");
 fw = new FileWriter("c:xy2.txt");
 char[] charBuffer = new char[1024];
 int len = 0;
 while ((len = fr.read(charBuffer)) != -1)
 {
 fw.write(charBuffer, 0, len);
 }
 System.out.println("文件复制成功");
 }
 catch (IOException e)
 {
 throw new RuntimeException("文件拷贝操作失败");
 }
 finally
 {
 try
 {
 if (null != fr)
 {
 fr.close();
 }
 }
 catch (IOException e)
 {
 throw new RuntimeException("关闭失败");
 }
 
try
 {
 if (null != fw)
 {
 fw.close();
 }
 }
 catch (IOException e)
 {
 throw new RuntimeException("关闭失败");
 }
 }
 }

(编辑:我爱制作网_潮州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读