`
xfei6868
  • 浏览: 69795 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Remember to properly close the File!

阅读更多
原文地址:http://www.javablogging.com/remember-to-properly-close-the-file/

    现在一些关于怎么样对待java中Files, Streams, Connections 和 其他任何"closeable"对象的一些建议。就简单的以FileWriter类和一段错误使用的它的bug代码:

public void writeToFile(String fileName, String content) {
    try {
      FileWriter file = new FileWriter(fileName);
      file.write(content);
    } catch (IOException e) {
      // Log the exception
    }
}



    有什么问题吗?哦,很多问题:我们没有验证input值(或许是null或者其他错误数据?),我们没有验证文件是否存在或者是一个问目录,我们没有注意指定文件的编码格式。除此之外你辩解说没有任何问题除了文件本身问题,约定认为:写文件就用FileWriter。也许是对的,但是仍然有一个事情是错的在这段代码中--我们没有 close 这个文件。

    这个很重要吗? 哦, 当然! 不关闭这个文件也许的结果就是导致写不能完成并系统一直占用文件不释放。一直要记住:colse这些Files, Streams, Connections!下面是我们经过权宜之后的解决bug的代码:
    public void writeToFile(String fileName, String content) {
        try {
            FileWriter file = new FileWriter(fileName);
            file.write(content);
            file.close();
        } catch (IOException e) {
            // Log the exeception
        }
    }


     解决了吗?我猜很多人认为它已经解决了。但是事实是没有解决—如果一个异常抛出在写的过程中呢?这个方法将退出,这个文件仍然没有close!好,我们来解决这个问题 — 用try/finally 解决。这种方式可以认为无论什么事情发生都将执行文件的close操作。

    public void writeToFile(String fileName, String content) {
        try {
            FileWriter file = new FileWriter(fileName);
            file.write(content);
        } catch (IOException e) {
            // Log the exeception
        } finally {
            file.close();
        }
    }


    解决了吗? 没有...如果finally块中这个文件将为null,异常仍然会被抛出在FileWriter结构。而且它将是NullPointerException,让我们修复它:

    public void writeToFile(String fileName, String content) {
        try {
            FileWriter file = new FileWriter(fileName);
            file.write(content);
        } catch (IOException e) {
            // Log the exeception
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }


    完成了吗?仍然很遗憾... file.close() 同样可能抛出异常!即使writeToFile没有任何验证异常在方法中抛出,我们任然要这样对付他们:

    public void writeToFile(String fileName, String content) {
        try {
            FileWriter file = new FileWriter(fileName);
            try {
                file.write(content);
            } finally {
                file.close();
            }
        } catch (IOException e) {
            // Log the exeception
        }
    }


    总之我们已经解决了这个问题修复了bug!注意这地方没不用在文件关闭之前非要验证这个文件是否为null,因为文件为null时候只有唯一在第3行抛出异常的情况下然后直接跳到第十行。当你关闭一个closeable object不是一个小事情,所以记住做这些!

    这里的另外一个问题就是可读性。以上代码对你是可以理解的,然后尝试并非一种closeable对象 - 那将会非常丑!因此你是否对付closeable对象最好的办法是把代码分解成两个方法:一个处理异常和关闭,另外的是处理业务主逻辑。想了解以上说法的具体代码可以看看下面:

    public void writeToFile(String fileName, String content) {
        try {
            FileWriter file = new FileWriter(fileName);
            try {
                performWriteToFile(file, content)
            } finally {
                file.close();
            }
        } catch (IOException e) {
            // Log the exeception
        }
    }


    // Here we perform all the operations on the file.
    // This method usually is much longer.
    private void performWriteToFile(FileWriter file,
            String content) throws IOException {
        file.write(content);
    }
0
0
分享到:
评论

相关推荐

    No suitable java found.In order to properly use the android developer tools...-附件资源

    No suitable java found.In order to properly use the android developer tools...-附件资源

    open file view

    This utility is especially useful if you try to delete/move/open a file and you get one of the following error messages: Cannot delete [filename]: There has been a sharing violation. The source or ...

    Mastering Android Application Development(PACKT,2015)

    Beyond this you’ll find out how to extend your app and add greater functionality, including notifications, location services, adverts and app billing (essential if you want to properly monetize your ...

    VclZip pro v3.10.1

    Fixed the SFX code so that it works properly if you use Copy /B to concatenate a zip file to the stub. Due to a Delphi strange behavior sometimes path names for directory only entries would become ...

    Java邮件开发Fundamentals of the JavaMail API

    javamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3 implementation comes with an SMTP and IMAP4 provider, besides the core classes. If you want to access a POP server ...

    Intergraph Standard File Formats (Element Structure)

    No, but there is a document that tries to indicate how to properly draw DGN elements given the structures returned by DGNLib. The OGR layer re-interprets the drawing information into OGR Feature Style...

    file_sync_linuxfilesync_filesync_文件同步_linux_properly61r_

    本文将详细解析如何利用TCP协议和JSON格式实现Linux下的简单文件同步,以及“properly61r”可能代表的优化策略。 首先,让我们了解TCP协议。传输控制协议(TCP)是互联网协议栈中的主力,它为应用程序提供了可靠的...

    word自动转化为chm

    /pAuto=1: Create the CHM file automatically and then close Word-2-CHM. /pOverwrite=1: Overwirte existing CHM file without prompts. Working with Security Software A connection to Microsoft Word is ...

    VC Exe打包捆绑程序

    PE format files as long as it does not modify the contents of the file header and file middle, just to add data to the end of the file, then the PE file can be run properly. This software can be ...

    drupal 6.12

    on an existing site, remember to copy all files from the original location to the new location. Some administrators suggest making the documentation files, especially CHANGELOG.txt, non-readable ...

    曲线拟合工具CurveExpert 1.0

    ct. 18, 1995 v. 1.00 =========================================================================== + First release of ... + The user was still asked whether to save a file or not upon exiting, even if ...

    OutlookAttachView v2.73

    enough disk space to store the saved file. The drawback of this mode: You cannot sort the attachments according to the column you choose with /sort command-line option. * Version 2.30 o Added '...

    Sakemail

    :)26/3/981.6.1- Added a FUNCFileName private variable to manage the complete path of the attached file. I receive problems reports with this, it work now ?.- Reduced the line sleep to 30 (tell me if ...

    索爱手机A2刷机软件

    Where as the phone file system contains lots of files needed for the phone to work properly. The phone FS also contains preloaded content like images and factory ringtones. With A2uploader you can ...

    ADB server didn't ACK && make sure the plugin is properly configure

    对于“ADB server didn't ACK && make sure the plugin is properly configure”这个问题,描述中提到的解决方案是针对端口被其他进程占用的情况。具体步骤如下: 1. **检查端口占用**:通过命令行工具(如Windows...

    eac3to V3.17

    * "eac3to some.mpls" now also works if the stream files aren't there, anymore * fixed: number of subtitles was not appended to demuxed subtitles' file name * fixed: dialnorm removal (for Nero decoder)...

    introduction to deep learning

    to properly attribute all ideas, since there is an abundance of quality material online (and the online world became very dynamic thanks to the social media). I will do my best to correct any mistakes...

    svn1.6.2使用帮助文档,svn帮助文档,如何使用svn

    integration with bug trackers properly), you can use the /bugid:"the bug id here"to do that. :add Adds the files in /pathto version control. :revert Reverts local modifications of a working copy. ...

Global site tag (gtag.js) - Google Analytics