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

一、错误示例1
public void fileCopy()
{
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 fileCopy()
{
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 fileCopy()
{
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("关闭失败");
}
}
}

Java的IO操作中关闭流的注意点,布布扣,bubuko.com

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

上一篇:蚁群算法求解旅行商问题 python


下一篇:C++反汇编->类,结构体,命名空间分析