Beispiel

public class ClassA {

public void makeStream (File file) {

try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(7);
//do something...

stream.close();

}
catch (IOException e) {
//stream leaked...
}
}
}



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


public class ClassA {

public void makeStream (File file) {

FileOutputStream stream = null;
try {
stream = new FileOutputStream(file);
stream.write(7);
//do something...

}
catch (IOException e) {
//do something...

}
finally {
if (stream != null) {
try {
stream.close();

}
catch(IOException e) {
//do something...

}
}
}
}
}