Java – fileoutputstream: does the “close” method also call “flush”?

I really care about the flush and close methods In my code, I always close my fileoutputstream object But I want to know, if I have to use the flush method here, where can I use it?

I will write a project and repeatedly Download 4 or 5 files I will write a method (for downloading files), and my method will cycle and download files repeatedly My method will have such code

Does the close method call flush, or must flush be used before closing?

try {
    InputStream inputStream = con.getInputStream();
    FileOutputStream outputStream = new FileOutputStream("C:\\programs\\TRYFILE.csv");

    int bytesRead = -1;
    byte[] buffer = new byte[4096];
    while ((bytesRead = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer,bytesRead);
}

} catch(Exception e) {
    //
} finally {
    outputStream.close();
    inputStream.close();
}

Note that the code works: it successfully downloaded the file But I don't know how to use flushing

Solution

The flush method is used to "Refresh" the bytes saved in the buffer Fileoutputstream does not use any buffers, so the flush method is empty Making a call will not change the result of your code

Using a buffer writer, this method calls close to explicitly refresh

So when you like to write data before closing the data stream, and before the buffer is full (when the buffer is full, the writer starts writing without waiting for a refresh call), you need to call flush

The source code of the fileoutputstream class does not have a custom version of the method flush So the flush method used is the version of its superclass OutputStream The code of flush in OutputStream is as follows

public void flush() throws IOException {
}

When you see that this is an empty method that does nothing, it's different to call it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>