Przykład

public class ClassA {

public void makeStream (File file) {

try {
FileInputStream stream = new FileInputStream(file);
stream.read();
//inne operacje...

stream.close();

}
catch (IOException e) {
//przeciek...
}
}
}



Rozwiązanie
Aby uniknąć przecieków zasobów, upewnij się, że dla każdej klasy java.io.FileInputStream jest wywoływana metoda close().
Uwaga: ta reguła ma zastosowanie do dowolnej postaci konstruktora FileInputStream.


public class ClassA {

public void makeStream (File file) {

FileInputStream stream = null;
try {
stream = new FileInputStream(file);
stream.read();
//inne operacje...

}
catch (IOException e) {
//inne operacje...

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

}
catch (IOException e) {
//inne operacje...

}
}
}
}
}