Beispiel

public class ClassA {

private FileInputStream stream;

public void makeStream (File file) {

try {
stream = new FileInputStream(file);
} catch(FileNotFoundException fnfe) {
//perform exception handling
}
//do something...

}
}



Lösung
Um Ressourcenlecks zu vermeiden, stellen Sie sicher, dass die Methode 'close()' für jedes Vorkommen von 'java.io.FileInputStream' aufgerufen wird. Hinweis: Diese Regel gilt für jede Form des Konstruktors 'FileInputStream'.


public class ClassA {

private FileInputStream stream;

public void makeStream (File file) {

try {
stream = new FileInputStream(file);
} catch(FileNotFoundException fnfe) {
//perform exception handling
}
//do something...

try {
stream.close();
} catch(IOException ioe) {
//perform exception handling
}
}
}