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会帮我们自动关闭,这是一种比较简单的处理方式


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM