在没有 try/catch 块的情况下关闭 InputStream?
Closing InputStream without a try/catch block?
我知道 InputStream
应该关闭。但我有些疑问在哪里以及如何做到这一点。
根据 IOUtils.closeQuietly 上的文档:
Unconditionally close an InputStream. Equivalent to
InputStream.close(), except any exceptions will be ignored. This is
typically used in finally blocks.
我的代码中不需要 try/catch
块,所以我没有 finally
块。在下面的方法中返回之前关闭 InputStream 是否可以,还是我应该做一些不同的事情?多个服务将使用此方法从文件加载 InputStream
。
public InputStream read(String filename) {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
if (inputStream == null) {
// Throw some exception
}
IOUtils.closeQuietly(inputStream);
return inputStream;
}
您根本不应该在此方法中调用 IOUtils.closeQuietly(inputStream);
- 返回已关闭的流没有什么意义。
但是,这个方法应该在try/finally块中调用:
InputStream is = null;
try {
is = read(filename);
// Do whatever with is.
} finally {
IOUtils.closeQuietly(is);
}
或使用 try-with-resources(注意 "try-with-resources statement will eliminate most needs for using IOUtils.closeQuietly
" 的评论 here):
try (InputStream is = read(filename)) {
// Do whatever with is.
}
try/finally块:
InputStream is = null;
try {
InputStream is =
is = read(filename);
// Do whatever with is.
} finally {
is.close();
}
注意:所有 i/o 资源都需要在 finally 块中关闭,因为它是在 try-catch 块中初始化的。还建议加上:
} catch(IOException e){
e.printstacktrace();
}
...用于异常处理
我知道 InputStream
应该关闭。但我有些疑问在哪里以及如何做到这一点。
根据 IOUtils.closeQuietly 上的文档:
Unconditionally close an InputStream. Equivalent to InputStream.close(), except any exceptions will be ignored. This is typically used in finally blocks.
我的代码中不需要 try/catch
块,所以我没有 finally
块。在下面的方法中返回之前关闭 InputStream 是否可以,还是我应该做一些不同的事情?多个服务将使用此方法从文件加载 InputStream
。
public InputStream read(String filename) {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
if (inputStream == null) {
// Throw some exception
}
IOUtils.closeQuietly(inputStream);
return inputStream;
}
您根本不应该在此方法中调用 IOUtils.closeQuietly(inputStream);
- 返回已关闭的流没有什么意义。
但是,这个方法应该在try/finally块中调用:
InputStream is = null;
try {
is = read(filename);
// Do whatever with is.
} finally {
IOUtils.closeQuietly(is);
}
或使用 try-with-resources(注意 "try-with-resources statement will eliminate most needs for using IOUtils.closeQuietly
" 的评论 here):
try (InputStream is = read(filename)) {
// Do whatever with is.
}
try/finally块:
InputStream is = null; try { InputStream is = is = read(filename); // Do whatever with is. } finally { is.close(); }
注意:所有 i/o 资源都需要在 finally 块中关闭,因为它是在 try-catch 块中初始化的。还建议加上:
} catch(IOException e){
e.printstacktrace();
}
...用于异常处理