Java的file.close()放在finally代碼塊報錯。本站提示廣大學習愛好者:(Java的file.close()放在finally代碼塊報錯)文章只能為提供參考,不一定能成為您想要的結果。以下是Java的file.close()放在finally代碼塊報錯正文
在學習Java的IO部分時有如下代碼:
import java.io.*;
public class InputFile {
public static void main(String [] args){
int a = 0;
FileInputStream file = null;
try {
file = new FileInputStream("G:\\java\\InputFile\\src\\InputFile.java"); //(1)
while((a = file.read()) != -1){
System.out.print((char)a);
}
} catch (IOException e){
System.out.println("文件讀取錯誤");
System.exit(-1);
}
finally{
if(file != null){
file.close();
}
}
}
}
一般都要將關閉資源.close()放在finally代碼塊中,防止try中發生異常資源沒有關閉,可上邊代碼報了IOException錯誤,當file.close();寫在try塊最後就沒有問題,原因是我把文件聲名
FileInputStream file = null;
放在try塊的外面,如果try中(1)執行失敗,將會拋出NullPointerException異常,此時file==null,不會執行file.close();如果(1)成功,關閉file時會拋出IOException異常,Java要求必須處理,所以需要在finally加一個try-catch塊。
finally{
if(file != null){
try{
file.close();
}
catch(IOException e){}
}
}
或者用java7或更晚的版本中出現的try-with-resources:
import java.io.*;
public class InputFile {
public static void main(String [] args){
int a = 0;
try (FileInputStream file = new FileInputStream("G:\\java\\InputFile\\src\\InputFile.java"))
{
while((a = file.read()) != -1){
System.out.print((char)a);
}
file.close();
} catch (IOException e){
System.out.println("文件讀取錯誤");
System.exit(-1);
}
}
}
總結:1.聲明FileInputStream需要在try塊外保證finally能訪問到
2.聲名時必須賦初值,否則如果在new時錯誤將出現編譯錯誤
3.file.close()會拋出IOException異常,需要處理
4.java7的新特性try-with-resources,
try(try-with-resources){
}
在try-with-resources中聲名資源,java會幫我們自動關閉,這是一種比較簡單的處理方式