1

希望这是一个关于 Java 中 BufferedOutputStreams 和 DataOutputStreams 的快速简单的问题。

当我将字节写入输出流时

myBufferedOutputStream.write(array);
myDataOutputStream.write(array);

这些方法是立即将它们写入流并返回还是阻塞?

我在核心 Java 文档中没有看到任何内容,但也许我的问题没有意义,因为写入从不阻塞?

有人请让我直截了当。

谢谢,jbu

4

4 回答 4

3

Peter's answer was the best, but it was vitiated by starting out with misinformation: no, it does not "depend on the implementation". The whole point of buffering is to soften the impact of blocking, but when the buffer is full and the output hardware not ready, write() WILL block. But since it is buffered, it will block far less often and with far less impact on throughput than a plain vanilla OutputStream. Buffering is a quick and easy way to make a big improvement in performance.

于 2010-11-20T02:34:05.097 回答
1

包 java.io.* 中的 API 可能会被阻塞。但是,有一个称为 Java NIO(新 I/O 或非阻塞 I/O)的特殊 API,您应该将其用于异步 I/O。

查看包 java.nio.* 你可以在这里找到一些例子:http ://en.wikipedia.org/wiki/New_I/O

于 2009-07-13T18:56:00.200 回答
1

中的所有读取和写入方法java.io.*都有可能阻塞。没有一个支持异步 I/O。对于阅读,必须使用.available()或类似机制手动实现。对于写作,好吧,你靠自己。

于 2009-07-02T18:35:13.503 回答
0

我相信这取决于实施。如果您使用类似的东西BufferedOutputStream,调用write()可能不会“阻塞”,因为该类提供了性能缓冲。

但是,如果使用FileOutputStream,则 write 调用可能会阻塞,具体取决于系统上 I/O 资源的繁忙/可用程度,因为此时调用 towrite()可能实际上会触发 I/O 操作,这需要时间才能完成。

于 2009-07-02T17:30:58.483 回答