不同位置关闭FileOutputStream的最佳编码实践

3
properties.storeToXML(new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
         "/" + m_wcontext.getServiceName() + ".properties")),null);

我在10个不同的地方都有一个类似的方法调用。在代码审查中,有人建议我需要关闭资源。推荐的方法是修改以下代码:但这将使代码变得笨重,因为我需要重复10次相同的代码。

try {
    fios = new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
                "/" + m_wcontext.getServiceName() + ".properties"));
    properties.storeToXML(fios, null);
} finally {
    if(fios!=null) {
         fios.close();
    }
}

你好,以下方法可以吗?还有更好的方法吗?
    FileOutputStream fios = getFileOutPutStream(m_wcontext.getProject().getBaseDirectory()  +  "/" + m_wcontext.getServiceName() + ".properties");        
    properties.storeToXML(fios, null);

    // ...      

private FileOutputStream getFileOutPutStream(String path) throws IOException {
    FileOutputStream fios=null;
    try {
        fios = new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
                "/" + m_wcontext.getServiceName() + ".properties"));
        properties.storeToXML(fios, null);
    } finally {
        if(fios!=null) {
            fios.close();
        }
    }
    return fios;
}

1
你使用的Java版本是什么? - Alfabravo
1个回答

3
假设您正在使用Java 7或更高版本进行编译,您可以使用try-with-resources语句来自动关闭资源:
private void writeXML(String path) throws IOException {
    try (FileOutputStream fios = new FileOutputStream(new File(path))) {
        properties.storeToXML(fios, null);
    }
}

我将方法设置为void,因为在将其作为参数传递给storeToXML后,您似乎不需要FileOutputStream

要调用此方法,可以使用以下代码:

String path = m_wcontext.getProject().getBaseDirectory() +
            File.separator + m_wcontext.getServiceName() + ".properties";

try {
    writeXML(path);
} catch (IOException e) {
    e.printStackTrace();
}

让我们假设,如果正在写入的文件非常大,同时又有另一个方法调用了相同的writeXML方法,那么这种情况会被处理吗?即在任务完成时两个资源都会被关闭。 - User27854
这取决于storeToXML的实现。只要文件不同并且适当地缓冲写入,我认为它应该可以工作。但是是的,在写入文件后,两个资源都将被关闭。 - Jacob G.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接