When does a stream close if its not closed manually?

后端 未结 6 2066
一个人的身影
一个人的身影 2021-01-04 10:27

I would like to know when does a stream close if its not closed manually. By this I mean, will the stream be closed if the scope of its reference is no more?

Conside

6条回答
  •  失恋的感觉
    2021-01-04 11:08

    That's a bad programming practice, an error from the programmer. Depending on the underlying data source, it might never close and you can have leaks. You MUST close any resource when you've finished with it, in a finally block, or using a try with resources if Java 7 or higher, to ensure it is closed even if an exception is thrown.

    InputStream in;
    OutputStream out;
    try {
       // Do your stuff with the streams
    } finally {
       if (in != null) {
           in.close();
       }
       if (out != null) {
           out.close();
       }
    }
    

提交回复
热议问题