Java 必须关闭缓冲区读取器
我正在尝试一个来自中国的例子 在本例中,Java 必须关闭缓冲区读取器,java,Java,我正在尝试一个来自中国的例子 在本例中,BufferReader未关闭是否需要关闭BufferReader?请解释一下 FileInputStream fstream = new FileInputStream("textfile.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; //Read File Line By Line while ((strLin
BufferReader
未关闭是否需要关闭BufferReader
?请解释一下
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
由于基础流已关闭,因此不一定要关闭
BufferedReader
,即使最好是按相反顺序(相对于打开顺序)关闭所有可关闭的
始终关闭溪流。这是一个好习惯,可以帮助你避免一些奇怪的行为。调用close()
方法也会调用flush()
,所以您不必手动执行此操作
关闭流的最佳位置可能是finally
块。如果您的示例中有这样一个异常,并且在.close()行中的之前发生异常,则流不会关闭
如果您有链接的流,您只能在最后一个流关闭之前关闭所有流。在您的示例中,这意味着br.close()
,而不是in.close()
示例
try {
// do something with streams
} catch (IOException e) {
// process exception - log, wrap into your runtime, whatever you want to...
} finally {
try {
stream.close();
} catch (IOException e) {
// error - log it at least
}
}
或者,您也可以在Apache Commons库中使用。从防止资源泄漏的角度来看,如果您还关闭了包装流所包装的流,则不一定要关闭包装流。但是,关闭包装流可能会导致内容丢失(特别是在输出情况下),因此最好关闭(仅)包装器,并依赖于记录的行为,即关闭包装器也会关闭包装流。(对于标准I/O包装器类来说,这当然是正确的!)
像Alexandr一样,我质疑依赖“玫瑰印度”的例子是否明智。例如,这一条中还有两个明显的错误,这是任何半正派的Java程序员都不应该犯的:
- 流在
finally
块中未关闭。如果在打开和关闭之间引发任何异常,则不会执行.close()中的in
语句,并且应用程序将泄漏打开的文件描述符。如果经常这样做,应用程序将开始抛出意外的IOException
s
- 链中的DataInputStream没有任何有用的用途。相反,它们应该使用
fstream
作为InputStreamReader
的参数。或者更好地使用FileReader
最后,这里是示例的更正版本:
BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
} finally {
// Close the reader stack.
br.close();
}
或者使用Java 7的“资源试用”:
这可能会有所帮助:请不要使用DataInputStream阅读文本。不幸的是,像这样的示例会被一次又一次地复制,所以您可以将其从示例中删除。不要使用来自rose india的代码。令人惊讶的是,错误或低质量代码的频率如此之高。如果在初始化BufferedReader时发生异常该怎么办?文件阅读器仍将打开。假设您在我的回答中谈论代码,是的,它将打开。请看BufferedReader源代码。然而,对于该构造函数,唯一可能的例外是OOME。
try (BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
}