示例

public class ClassA {

private FileOutputStream stream;

public void makeStream (File file) {

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

}
}



解决方案
为了避免资源泄漏,请确保对每个 java.io.FileOutputStream 都调用 close()。注意:此规则适用于所有形式的 FileOutputStream 构造函数。


public class ClassA {

private FileOutputStream stream;

public void makeStream (File file) {

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

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