Do I need to surround fileInputStream.close with a try / catch / finally block? How it's done?

I have the following Java class that does one thing, it returns values โ€‹โ€‹from config.properties.

When the time comes to close fileInputStream, I think I read on Wikipedia that itโ€™s good to have it in the finally block. Because it honestly works great in a try / catch block.

Can you show me the correction to get fileInputStream.close()at the end of the section?

ConfigProperties.java package database;

import java.io.FileInputStream;
import java.util.Properties;

public class ConfigProperties {

    public FileInputStream fileInputStream;
    public String property;

    public String getConfigProperties(String strProperty) {

        Properties configProperties = new Properties();
        try {

            fileInputStream = new FileInputStream("resources/config.properties");
            configProperties.load(fileInputStream);
            property = configProperties.getProperty(strProperty);
            System.out.println("getConfigProperties(" + strProperty + ")");

            // use a finally block to close your Stream.
            // If an exception occurs, do you want the application to shut down?

        } catch (Exception ex) {
            // TODO
            System.out.println("Exception: " + ex);
        }
        finally {
            fileInputStream.close();
        }

        return property;
    }
}

Is this solution only what Eclipse offers and do it in a finally block?

finally {
    try {
        fileInputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Thanks everyone!

+5
source share
3 answers

FileInputStream.close() IOException, finally {} . , . Eclipse ; IOException finally {}.

+7

, Java 7. Java 7 try -with-resource, , try :

try (FileInputStream fileIn = ...) {
    // do something
} // fileIn is closed
catch (IOException e) {
    //handle exception
}
+11

Standard approach:

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
    }
}
+7
source

All Articles