範例

public class ClassA {

public void makeStream (InputStream iStream) {

try {
InputStreamReader stream = new InputStreamReader(iStream);
stream.read();
//執行某種動作...

stream.close();

}
catch (IOException e) {
//洩漏串流...
}
}
}



解決方案
若要避免資源洩漏,請確定在每個 java.io.InputStreamReader 上都呼叫了 close()。
附註:這個規則適用於任何形式的 InputStreamReader 建構子。


public class ClassA {

public void makeStream (InputStream iStream) {

InputStreamReader stream = null;
try {
stream = new InputStreamReader(iStream);
stream.read();
//執行某種動作...

}
catch (IOException e) {
//執行某種動作...

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

}
catch(IOException e) {
//執行某種動作...

}
}
}
}
}