gpt4 book ai didi

java - 我需要在那里显式使用 flush() 方法吗?

转载 作者:行者123 更新时间:2023-12-04 08:14:28 26 4
gpt4 key购买 nike

我需要在那里明确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?
}
}

最佳答案

来自 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.

关于java - 我需要在那里显式使用 flush() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65780687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com