如何确保一个 I/O 流的关闭?

118*_*218 0 java io

考虑这个函数:

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

如何在异常和错误的情况下关闭流?

Ell*_*sch 5

正如发布的那样,你可以使用finally像这样的块

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,编写该while循环的更惯用的方法是

void print(Reader reader) throws IOException {
    int code;
    while ((code = reader.read()) != -1) {
        System.out.print((char) code);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用try-with-resources来自调用者的 a;喜欢

try (Reader reader = ...) {
    print(reader);
}
Run Code Online (Sandbox Code Playgroud)