我是否需要显式显示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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句