在各个位置关闭FileOutputStream的最佳编码实践

时间:2018-04-12 13:44:17

标签: java fileoutputstream

'Cannot attach additional subparts to non-multipart/*')
email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/*

我在10个不同的地方进行了类似的方法调用。在代码审查期间,建议我需要关闭资源。建议的方法是使用修改代码如下:但这将使代码笨拙,因为我需要重复代码10次。

properties.storeToXML(new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
         "/" + m_wcontext.getServiceName() + ".properties")),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();
    }
}

1 个答案:

答案 0 :(得分: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,因为在将FileOutputStream作为参数传递给storeToXML后,您似乎不需要String path = m_wcontext.getProject().getBaseDirectory() + File.separator + m_wcontext.getServiceName() + ".properties"; try { writeXML(path); } catch (IOException e) { e.printStackTrace(); }

要调用此方法,您可以使用以下内容:

pictureBoxLiveCamera