[英]Do I need to explicitly use flush() method there?
我是否需要明确地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 */
因此,如果您需要保证字节被写入下一个 stream,请调用它。
请查看checkError
根据其文档:
* Flushes the stream if it's not closed and checks its error state.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.