Search code examples
javafileoutputstream

Best coding practice for closing of FileOutputStream at various location


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

I have a similar method call at 10 different places. During the code review it was suggested that I need to close the resource. The recommended method was to use modify the code as below: but that will make the code clumsy as I need to repeat the code 10 times.

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

Will the below approach is fine. is there anything better?

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

Solution

  • Assuming that you're compiling with Java 7 or above, you can use a try-with-resources statement to automatically close the resource:

    private void writeXML(String path) throws IOException {
        try (FileOutputStream fios = new FileOutputStream(new File(path))) {
            properties.storeToXML(fios, null);
        }
    }
    

    I've made the method void, as it looks like you have no need for the FileOutputStream after passing it as an argument to storeToXML.

    To call this method, you can use the following:

    String path = m_wcontext.getProject().getBaseDirectory() +
                File.separator + m_wcontext.getServiceName() + ".properties";
    
    try {
        writeXML(path);
    } catch (IOException e) {
        e.printStackTrace();
    }