catalogue
0.1 briefly describe the reason why the close() method closes the flow during development
4. Interview question: what else can I do to close the flow without closing
Closing condition of stream in java
0.0 application scenario
- File transfer (copying files, deleting files or folders, renaming files, etc.)
- Network transmission (data reading, uploading and downloading from the server)
- Storage of hard disk data
All streams, whether input or output, should be closed after use. If it is not closed, it will waste resources. When the equivalent is large, it will affect the normal development of business.
0.1 briefly describe the reason why the close() method closes the flow during development
Why use close() to close the stream? Isn't it automatically recycled by gc when the program ends?
Briefly describe the reason why the close() method closes the flow during development
I. because the user has no way to control the garbage collection of java, it will be triggered when it is uncertain, and java does not guarantee that the garbage collection will be triggered during the whole program running period, so it must be closed after the resources such as streams and sockets are used up. Moreover, for objects such as socket and thread, even if the reference count is 0, the garbage collection mechanism will not be recycled as long as it is still active.
2. The stream not only allocates space in memory, but also occupies resources in the operating system. java's gc can reclaim unused objects from memory, but it can't do anything about the resources allocated by the operating system. Therefore, it is necessary to call the close() method to notify the OS to release this resource.
Why do you have to close()?
A: turn the stream object into garbage so that it can be recycled by the garbage collector
B: notify the system to release the resources related to the file
Step 1: close in try
Close the file input stream in the scope of try. In the previous examples, this method is used. This has a disadvantage;
If the file does not exist, or an exception is thrown due to a problem when reading, this line of code to close the flow will not be executed, resulting in a huge hidden danger of resource occupation. Not recommended.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { try { File f = new File("d:/lol.txt"); FileInputStream fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } // Close flow in try fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Step 2: close in finally
How to close the stream in JAVA
This is the standard way to close the flow
1. First, declare the reference of the stream outside the try. If it is declared inside the try, its scope cannot reach finally
2. Before finally closing, judge whether the reference is empty
3. When closing, you need to try catch again
This is a standard and rigorous way to close the flow, but it seems very cumbersome. Therefore, when writing unimportant or testing code, the above hidden try method will be adopted, because it is not troublesome~
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/lol.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } finally { // Close the flow in finally if (null != fis) try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Step 3: use try()
Use the try with resource mechanism to close the connection
A major feature of JAVA is that the JVM will automatically recycle internal resources, that is, automatic GC, which brings great convenience to developers. However, the JVM's reference to external resources cannot be recycled automatically, such as database connections, network connections and input / output IO streams. These connections need to be closed manually, otherwise external resources will be leaked, connection pool overflow and abnormal file occupation.
The traditional manual release of external resources is generally placed in the finally code block of the try{}catch(){}finally {} mechanism, because the statements in the finally code block will be executed, that is, it ensures that the external resources will be released in the end. At the same time, considering that exceptions may occur in the finally code block, there is also a try{}catch() {} in the finally code block. This writing method is a classic traditional method of releasing external resources, which is obviously very cumbersome.
JDK1. After 7, there is a try with resource processing mechanism. First, the resources that are automatically closed need to implement the Closeable or autoclosable interfaces, because only when these two interfaces are implemented can the close() method be automatically called to automatically close the resources. The writing method is try(){}catch() {}. The external resources to be closed are created in try(), and catch() catches and handles exceptions. In fact, the try with resource mechanism is a syntax sugar, and its underlying implementation principle is still the writing method of try{}catch(){}finally {}, but there is an addresssuppressed () method in the catch() {} code block, that is, the exception suppression method. If exceptions occur in both business processing and connection closing, the business processing exception will suppress the connection closing exception and only throw the exception in processing. The connection closing exception can still be obtained through the getSuppressed() method.
Compared with the traditional try{}catch(){}finally {} mechanism, the try with resource processing mechanism has this exception suppression method, which helps us simplify the handling of exceptions when closing the connection.
Define the flow in try(). When try,catch or finally ends, it will be closed automatically
This way of writing code is called try with resources, which is a technology supported from JDK7
All streams implement an interface called autoclosable. Any class that implements this interface can be instantiated in try(). It will be automatically closed at the end of try, catch and finally to recycle relevant resources.
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/lol.txt"); //Define the flow in try(). When try,catch or finally ends, it will be closed automatically try (FileInputStream fis = new FileInputStream(f)) { byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } } }