考虑这个函数:
import java.io.IOException;
import java.io.Reader;
class StreamPrinter {
void print(Reader reader) throws IOException {
int code = reader.read();
while (code != -1) {
System.out.print((char) code);
code = reader.read();
}
reader.close();
}
}
出现异常和错误时如何关闭流?
最佳答案
正如发布的那样,您可以使用 finally
block ,例如
void print(Reader reader) throws IOException {
try {
int code = reader.read();
while (code != -1) {
System.out.print((char) code);
code = reader.read();
}
} finally {
reader.close();
}
}
此外,编写 while
循环的更惯用方法类似于
void print(Reader reader) throws IOException {
int code;
while ((code = reader.read()) != -1) {
System.out.print((char) code);
}
}
然后使用调用者的try-with-resources
;喜欢
try (Reader reader = ...) {
print(reader);
}
关于java - 如何保证一个I/O流的关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238587/