Java IO is a big knowledge point.
If you break down its knowledge points and talk about it, it will probably be a week. For the IO system, you can take a look at the following picture.
Next, let's start with a piece of code, let's take a look at the following code
public class Test { public static void main(String[] args) throws Exception { File file = new File("text.txt"); if(!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] b = new byte[1024]; bos.write(b); bos.flush(); }} A buffered stream is constructed in the code, and then a KB-length data is written into the stream, and finally the flush() method is called.
This is a very simple piece of code, and the final output is to generate a 1KB text.text file.
But if we comment out the last line
//bos.flush();
The final generated text.text size will become 0.
This result is very obvious, but if we change flush() to close(), will the result still be 0?
About flush
Flush() is actually found in network transmission a long time ago
At that time, for efficiency, the server and the client would not transmit a piece of data every time it was generated.
Instead, a buffer will be created and data will be transferred to the client after the buffer is full.
Sometimes there is such a problem. When the data is not enough to fill the buffer and data needs to be transmitted to the client, in order to solve this problem, there is a concept of flush, and the buffer data is forced to be sent.
Going back to the above question, is it feasible to replace flush with close
The answer is yes.
If you look at the source code, you will know the inheritance relationship of BufferedOutputStream
public class BufferOutputStream extends FilterOutputStream
BufferedOutputStream does not implement the close() method, so it will directly call the close() of FilterOutputStream, and the close() method of FilterOutputStream will call flush() to output the buffer data.
In actual development, regarding IO operations, it is emphasized that the close() method must be called in the end. The above example is one of the reasons.