289
汽車大全
Java的IO操作中關閉流的注意點
一、錯誤示例1public 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("關閉失敗");
}
}
}
最後更新:2017-04-03 12:56:11