do I need to surround fileInputStream.close with a try/catch/finally block? How is it done?

后端 未结 3 467
失恋的感觉
失恋的感觉 2021-01-05 06:16

I have the following Java Class that does one thing, fires out values from config.properties.

When it comes time to close the fileInputStream

3条回答
  •  离开以前
    2021-01-05 07:03

    The standard approach is:

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(...);
        // do something with the inputstream
    } catch (IOException e) {
        // handle an exception
    } finally { //  finally blocks are guaranteed to be executed
        // close() can throw an IOException too, so we got to wrap that too
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }        
        } catch (IOException e) {
            // handle an exception, or often we just ignore it
        }
    }
    

提交回复
热议问题