Muss ich fileInputStream.close mit einem try / catch / finally-Block umgeben? Wie wird es gemacht?

Ich habe die folgende Java-Klasse, die eine Sache tut, löst Werte von config.properties aus.

Wenn es Zeit ist, das zu schließenfileInputStreamIch glaube, ich habe auf Wikipedia gelesen, dass es gut ist, es in einem finalen Block zu haben. Weil es ehrlich gesagt im Try / Catch-Block gut funktioniert.

Kannst du mir Korrektur zeigen um das zu bekommenfileInputStream.close() in einem letzten abschnitt?

ConfigProperties.java-Paketbasis;

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

Ist die Lösung nur zu tun, wie es Eclipse vorschlägt, und dies im finally-Block zu tun?

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

Vielen Dank an alle!

Antworten auf die Frage(3)

Ihre Antwort auf die Frage