如果它们通过java包装在缓冲区中,我是否必须明确关闭所有流?

时间:2015-12-03 19:01:19

标签: java networking

private InputStream input;
private InputStreamReader inputReader;
private BufferedReader reader;

try {
    input = new InputStream();
    inputStreamReader = new InputStreamReader(inputStream);
    reader = new BufferedReader(inputStreamReader);
    // do I/O operations
} catch (IOException e) {
    Log.d("IOException", "The Data Could Not Be Read =/");
} finally {
    try {
        reader.close(); // now will this, by default, close all other streams? OR
      /*
       * input.close(); inputStream.close(); //is this necessary, along with
       * reader.close();
       */
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

我今天遇到了这个问题,并且不确定它们是否会被关闭,因为它已被包裹,或者是否仍然需要关闭所有流 独立地

3 个答案:

答案 0 :(得分:8)

如果任何阅读器或流装饰另一个阅读器/流,则关闭外部阅读器或流也会关闭内部。这可以从Closeable#close()的Javadoc暗示:

  

关闭此流并释放与其关联的任何系统资源。

这也适用于底层资源。

如果你很好奇,你可以深入研究这些课程的来源,例如。在BufferedReader

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

其中in是基础Reader

答案 1 :(得分:5)

是的,装饰的溪流也关闭了。

InputStream in = new FileInputStream("c:\\myfile.txt");
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(reader);

bufferedReader.close();

in.read(); // throws an IOException (no such file or directory)
reader.read(); // throws an IOException (Stream closed)

答案 2 :(得分:4)

从Java 7开始,您可以使用try-with-resource块(以及关闭reader关闭其他块的事实)

try (BufferedReader reader = new BufferedReader(
                              new InputStreamReader(new FileInputStream(file), "UTF-8"))) {

    // do I/O operations
} catch(IOException e) {
    Log.d("IOException", "The Data Could Not Be Read =/", e);
}