【问题标题】:Do I need to explicitly use flush() method there?我需要在那里显式使用 flush() 方法吗?
【发布时间】:2021-04-23 02:45:12
【问题描述】:

我是否需要明确地writer.flush()?我认为离开save() 方法后writer 可能不会向outputStream 写入数据

import java.io.*;

public class Test
{
    public int i = 5;
    
    public void save(OutputStream outputStream) throws Exception
    {
        PrintWriter writer = new PrintWriter(outputStream);
        writer.println(i);
        writer.flush(); // necessarily or not?
    }
}

【问题讨论】:

  • 如果你在某个时候关闭输出流,则不会。
  • 这只是您何时要将数据刷新到输出流的问题。正如大牛指出的那样,关闭 PrintWriter 也会刷新它。您需要在程序中的某个时刻以某种方式刷新它,否则无法保证数据会进入输出流,但是如果没有看到其余代码,很难说您是否需要该特定行.
  • 我知道如果关闭外部流内部流也​​会被关闭,并且知道如果不刷新()或关闭()外部流数据将不会被保存。但我不知道 PrintWriter/BufferedWriter 或其他外部流是否立即将数据发送到内部流。例如,如果我不使用 close() 或 flush() 函数,PrintWriter 包含我发送给它的数据并在离开 save() 函数而不向内部流发送数据后丢失它的情况?
  • 您也可以使用 CTOR PrintWriter writer = new PrintWriter(outputStream, true);。 true 标志用于自动刷新。每次调用任何 println() 方法或使用 format() 方法之一时,都会检查并执行 autoflush。他们调用内部的 newLine() 方法,自动刷新在其中得到检查和执行。查看 PrintWriter 的源代码,在那里你可以看到它的行为。最好下载 Java 源代码包并将其链接到您的 IDE 中,您可以轻松直接地访问它。

标签: java flush


【解决方案1】:

来自flush 文档:

 /**
  * Flushes the stream.  If the stream has saved any characters from the
  * various write() methods in a buffer, write them immediately to their
  * intended destination.  Then, if that destination is another character or
  * byte stream, flush it.  Thus one flush() invocation will flush all the
  * buffers in a chain of Writers and OutputStreams.
  *
  * <p> If the intended destination of this stream is an abstraction provided
  * by the underlying operating system, for example a file, then flushing the
  * stream guarantees only that bytes previously written to the stream are
  * passed to the operating system for writing; it does not guarantee that
  * they are actually written to a physical device such as a disk drive.
  *
  * @throws java.io.IOException
  *          If an I/O error occurs
  */

因此,如果您需要保证字节被写入下一个流,请调用它。

请查看checkError,根据其文档:

* Flushes the stream if it's not closed and checks its error state.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2015-08-12
    • 2015-10-19
    • 2022-01-19
    • 2019-08-02
    相关资源
    最近更新 更多