Java如何正确的使用try catch finally关闭文件流的总结

来源:互联网 发布:python项目源代码下载 编辑:程序博客网 时间:2024/06/01 16:22

上学的时候,也许老师告诉你用完文件流记得要关闭,可能为了省事,他也没仔细的给你示范如何关闭,
实际开发中,要是不能正确关闭流,服务器分分钟炸掉,那是很正常的。
一般都是新人才会有这个问题。当然都是从新人走过来的嘛。
下面是大师兄总结的关闭文件流的基本动作,有不合适的,还请指出来。


流在try外面声明,在try里面初始化,然后在finally里面给close,还记得处理异常e
finally里面close的时候也得再次try catch 一下。
具体代码和具体的解释如下:

    /**     * 测试正确关闭文件流     */    private static void testCloseFileStream() {        final Logger LOG = LoggerFactory.getLogger(Cmshome.class);        String fileName = "";        InputStream inputStream = null;//声明个引用,因为这个new对象的时候也是会异常的        try {            //这里就会异常,如果文件名不存在的话。            inputStream = new FileInputStream(fileName);        } catch (IOException e) {            //这个主要是把出现的异常给人看见,不然就算异常了,看不到就找不到问题所在。            LOG.debug("loadProperties IOException:" + e.getMessage());        } finally {            if (inputStream != null) {                try {                    inputStream.close(); // 关闭流                } catch (IOException e) {                    LOG.debug("inputStream close IOException:" + e.getMessage());                }            }        }    }//错误的关闭文件的方式的解释:Properties properties = new Properties();try {//这要是异常,直接就到catch语句,下面的close就不会执行啦,关闭就没用啦InputStream wrongWay = new FileInputStream(fileName);properties.load(wrongWay);wrongWay.close(); // 关闭流} catch (IOException e) {e.printStackTrace();}//下面是new文件流和关闭文件流的源码,有抛异常动作。    public FileInputStream(String name) throws FileNotFoundException {        this(name != null ? new File(name) : null);    }//这个是抽象类(abstract class)里面的方法,所以没有具体实现过程。    public void close() throws IOException {}





4 0
原创粉丝点击