All streams, either input or output streams flow, after use, should be closed. If you do not shut down, it will produce a waste of resources consumed. Equivalent relatively large, will affect the normal conduct of business.
Step 1: Close the try
Step 2: In the finally closed
Step 3: try () manner
Step 4: Practice - Close Flow
Step 5: The answer - Close stream
Step 1: Close the try
Scope try to close the file in the input stream, in the previous example is to use this way of doing this has a drawback;
if the file does not exist, or read something goes wrong and throws an exception, then it will not this line of code to perform closed stream, there is a huge resource consumption risks. Not recommended for use
|
Step 2: in the finally closed
This is the standard way to shut down the flow
1. First, the reference flow statement outside try, if declared try it, its scope can not be arrived finally.
2. Before finally closed, it must first determine whether the reference is empty
3 Close, when need be once again try catch process
which is the standard way to shut down the flow of rigorous, but it seems very complicated, so write test code unimportant or that they will adopt the above have hidden way of try, because they do not trouble ~
|
Step 3: use the try () manner
把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
这种编写代码的方式叫做 try-with-resources, 这是从JDK7开始支持的技术
所有的流,都实现了一个接口叫做 AutoCloseable,任何类实现了这个接口,都可以在try()中进行实例化。 并且在try, catch, finally结束的时候自动关闭,回收相关资源。
|