我需要在那里明确使用 flush() 方法吗?
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
*/
因此,如果您需要保证将字节写入下一个流,请调用它。
请查看 checkError
,根据其文档:
* Flushes the stream if it's not closed and checks its error state.
我是否需要明确地 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.