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

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

问题描述

我对刷新和关闭方法真的很困惑.在我的代码中,我总是关闭我的 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.

close 方法是否调用了 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 不使用任何缓冲区,因此刷新方法为空.调用与否不会改变代码的结果.

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(当缓冲区已满时,编写器无需等待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).

FileOutputStream 类的源代码没有自定义版本的方法 flush.所以使用的flush方法是其超类OutputStream的版本.OutputStream中flush的代码如下

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天全站免登陆