Java的IO操作中关闭流的注意点

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                一、错误示例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根本就没有初始化,执行③的时候就会报空指针异常。②④同样是这个道理。


二、错误示例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("关闭失败");
}
}
}
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hdsghtj/article/details/83956259