读书人

Remember to properly close the File

发布时间: 2012-12-19 14:13:15 作者: rapoo

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);            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);    }

读书人网 >操作系统

热点推荐