FileOutputStream:“关闭”吗?方法调用也“刷新”? [英] FileOutputStream: Does the "close" method calls also "flush"?

查看:217
本文介绍了FileOutputStream:“关闭”吗?方法调用也“刷新”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对flush和close方法感到困惑。在我的代码中,我总是关闭 FileOutputStream 对象。但我想知道如果我必须在这里使用flush方法,我可以在哪里使用它?

I'm really confused about flush and close method.In my code I always close my FileOutputStream object. But I want to know that if I have to use flush method here, and where can I use it?

我将编写一个重复下载4或5个文件的项目。我将编写一个方法(用于下载文件),我的方法将循环并重复下载文件。我的方法将有这样的代码。

I will write a project that download 4 or 5 files repeatedly. I will write a method(for download files) and my method will be in a loop and download files repeatedly.My method will have a code like this.

是否关闭方法调用 flush ,还是我必须在关闭前使用flush?

Does the close method calls flush, or do I have to use flush 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, 0, bytesRead);
}

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

请注意,代码运行良好:它成功下载文件。但我不确定使用 flush

Note that the code works well: it download the file successfully. But I'm not sure about using flush.

推荐答案

方法 flush 用于刷新缓冲区中保留的字节。 FileOutputStream 不使用任何缓冲区,因此flush方法为空。调用与否不会改变代码的结果。

The method flush is used to "flush" bytes retained in a buffer. FileOutputStream doesn't use any buffer, so flush method is empty. Calling it or not doesn't change the result of your code.

对于缓冲编写器,方法 close 显式调用 flush

With buffered writers the method close call explicitly flush.

所以你需要在关闭流之前写入数据时调用flush 并且在缓冲区已满之前(当缓冲区已满时,编写器开始写入而不等待刷新调用)。

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

类<$ c的源代码$ c> FileOutputStream 没有自定义版本的方法 flush 。因此使用的 flush 方法是其超类 OutputStream 的版本。 OutputStream 中的刷新代码如下:

The source code of class FileOutputStream hasn't a custom version of method flush. So the flush method used is the version of its super class OutputStream. The code of flush in OutputStream is the following

public void flush() throws IOException {
}

如你所见,这是一个无效的空方法,所以调用与否是相同的。

As you see this is an empty method doing nothing, so calling it or not is the same.

这篇关于FileOutputStream:“关闭”吗?方法调用也“刷新”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆