应该显式关闭BufferedReader和InputStreamReader吗? [英] Should BufferedReader and InputStreamReader be closed explicitly?
问题描述
我想将 InputStream
的内容读入字符串
:
private String readToString(InputStream stream) {
return new BufferedReader(new InputStreamReader(stream))
.lines().collect(Collectors.joining("\n"));
}
流来自 java.lang.Process
。
问题:我是否必须显式关闭任何 InputStream
,<$在这种情况下,c $ c> InputStreamReader 或 BufferedReader
?
Question: Do I have to explicitly close any of the InputStream
, InputStreamReader
or BufferedReader
in this case?
旁注:链接问题是不重复,因为我的问题是 HOW 正确关闭流,而不是如何将流读取到字符串!
Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!
推荐答案
您只需要关闭外部
包装器,但不要明确地这样做 - 那里是尝试使用资源,让您的生活更轻松:
You only need to close the outer
wrapper, but don't do that explicitly either way - there is try-with-resource that will make your life easier:
public String readToString(InputStream stream) {
try (InputStreamReader reader = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(reader)) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
还有一个很多更简单的方法,更清晰:
There is also a much easier way to do that and way more clear:
Files.readAllLines(YourPath)
这篇关于应该显式关闭BufferedReader和InputStreamReader吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!