java中io流的flush()函数起的作用???
在java的输出流中,经常能看到有flush()这个函数,在jdk中的解释是刷新缓冲区,向其下属流对象输出数据
“Flushes this data output stream. This forces any buffered output bytes to be written out to the stream.
The flush method of DataOuputStream calls the flush method of its underlying output stream”
我写了一段代码测试了一下,发现在程序里如果不调用flush()方法数据仍然可以被下一级对象得到,代码如下:
import java.io.*;
public class FlushTest
{
public FlushTest()
{
}
public static void main(String args[])
{
String strings[] =
{
"a", "b", "c", "d", "e"};
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(
byteArrayOutputStream);
try
{
for (int i = 0; i < strings.length; i++)
{
dataOutputStream.writeBytes(strings[i]);
// dataOutputStream.flush();
System.out.println("the " + i + "th time to write it is: " +
new String(byteArrayOutputStream.toByteArray()));
byteArrayOutputStream.reset();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
不管加不加flush()那一行,输出结果都是
the 0th time to write it is: a
the 1th time to write it is: b
the 2th time to write it is: c
the 3th time to write it is: d
the 4th time to write it is: e
谁能解释一下怎么回事?