一、錯誤示例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("關閉失敗");
}
}
}