我理解流是字节序列的表示。每个流都提供了将字节读写到其给定的后备存储的方法。但溪流的意义何在?为什么后台存储本身不是我们交互的对象?

不知什么原因,我就是不喜欢这个概念。我读了很多文章,但我觉得我需要一个类比。


当前回答

之所以选择“流”这个词,是因为它(在现实生活中)与我们使用它时想要传达的意思非常相似。

Start thinking about the analogy to a water stream. You receive a continuous flow of data, just like water continuously flows in a river. You don't necessarily know where the data is coming from, and most often you don't need to; be it from a file, a socket, or any other source, it doesn't (shouldn't) really matter. This is very similar to receiving a stream of water, whereby you don't need to know where it is coming from; be it from a lake, a fountain, or any other source, it doesn't (shouldn't) really matter. source

其他回答

流是字节序列的抽象。其思想是,您不需要知道字节来自何处,只需以标准化的方式读取它们。

例如,如果你通过流处理数据,那么数据来自文件、网络连接、字符串、数据库中的blob等等,对你的代码来说都无关紧要。

与备份存储本身交互本身并没有什么问题,除了它将您绑定到备份存储实现。

把流看作是抽象的数据源(字节、字符等)。它们抽象了具体数据源的实际读写机制,可以是网络套接字、磁盘上的文件或来自web服务器的响应。

A stream is a highly abstracted metaphor and a strict contract. It means that you can manipulate objects in sequence without concern about gaps. That is to say, a stream must have no vacuum or gaps. Objects in it are arranged in sequence one by one continuously. As a result, we don't have to worry about encountering a vacuum abruptly in the midst of processing a stream, or we can't leave a vacuum deliberately when producing a stream. In other words, we don't have to consider the case of a void in processing or producing a stream. There is no way we can come across it or produce it on purpose. If you are constructing a stream, you must not leave any gaps in the stream.

换句话说,如果有一个缺口,它一定不是一个流。当您将序列称为流时,要么您被保证其中没有空白,要么您必须信守您所生成的序列中没有空白的承诺。

回顾一下,想象一条水流。它最大的特点是什么?

连续!

溪流的抽象精神就是关于它的。

关键是你不应该知道后台存储是什么——它只是一个抽象。实际上,甚至可能没有备份存储——您可能正在从网络中读取数据,而数据根本就没有“存储”。

如果你写的代码能够在文件系统、内存、网络或任何支持流思想的东西上工作,那么你的代码就会更加灵活。

此外,流通常是链接在一起的——你可以有一个流来压缩放入其中的任何内容,将压缩的表单写入另一个流,或者加密数据,等等。在另一端是反向链,解密,解压缩等等。

除了上面提到的东西,还有一种不同类型的流——在函数式编程语言(如Scheme或Haskell)中定义的流——一种可能无限的数据结构,由一些函数按需生成。