java中io流的flush()函数起的作用???

findfrog 2004-08-23 09:45:31
在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

谁能解释一下怎么回事?

...全文
2120 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Lulq21cn 2004-08-24
  • 打赏
  • 举报
回复
ChDw(米) 说的有理,在有的例子中刷新显得尤为重要,如客户和服务器在进行数据传送的时候若刷新没有发生,那么信息不会进入网络,除非缓冲区满(溢出),这会带来许多问题。
其实你可以参考TIJ中的第15章 网络编程中的例子。


MaoZhua 2004-08-24
  • 打赏
  • 举报
回复
flush()的作用是清空缓冲区!
ChDw 2004-08-24
  • 打赏
  • 举报
回复
你可以试试使用BufferedOutputStream之类的,如果你不flush就可能会没有真正发出

没有flush不代表它就不发出,只是可能没有完全发出。调用flush是保证缓存清空发出
alabaza 2004-08-24
  • 打赏
  • 举报
回复
flush() 就是把缓冲区冲掉,就像。。。比喻太恶心,不说了。
registered 2004-08-23
  • 打赏
  • 举报
回复

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;

public class FlushTest {
public static void main(String args[]) {
String strings[] = {"a", "b", "c", "d", "e"};
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedOutputStream buff = new BufferedOutputStream(out);
try {
for (int i = 0; i < strings.length; i++) {
buff.write(strings[i].getBytes("UTF-8"));
buff.flush(); // TODO: COMMENT THIS
System.out.println("the " + i + "th time to write it is: " +
new String(out.toByteArray()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

flush() 只用在 BufferedStream 上面

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧