如何确保此方法关闭OutputStream以避免内存泄漏?
public static void store(Properties properties, Class script) throws IOException {
ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class);
if (scriptManifest != null) {
String name = scriptManifest.name();
FileOutputStream outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties");
properties.store(outputStream, "");
outputStream.close();
} else {
throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest.");
}
}
答案 0 :(得分:2)
您可以使用try-with-resources。例如:
public static void store(Properties properties, Class script) throws IOException {
ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class);
if (scriptManifest != null) {
String name = scriptManifest.name();
try ( FileOutputStream outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties") ) {
properties.store(outputStream, "");
}
} else {
throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest.");
}
}
或尝试使用finally块:
public static void store(Properties properties, Class script) throws IOException {
ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class);
if (scriptManifest != null) {
String name = scriptManifest.name();
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties");
properties.store(outputStream, "");
} finally {
if ( outputStream != null ) outputStream.close();
}
} else {
throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest.");
}
}
答案 1 :(得分:1)
有两种方法。
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(...)
...
}
catch (IOException e) {
throw new RuntimeException(...)
}
finally {
// or use the Apache Commons IOUtils.closeQuietly(outputStream);
// and then only need the one line
if (outputStream != null) {
try {
outputStream.close();
}
catch (Exception ignore) { }
}
}
在Java的更高版本中,您可以使用try-with-resources
try (FileOutputStream fos = new FileOutputStream("f:/tmp/stops.csv")) {
}
catch (IOException e) {
}