我想知道是否有任何理想的方式可以将多个 InputStream 链接到 Java(或 Scala)中的一个连续 InputStream 中。
我需要它来解析我从 FTP 服务器通过网络加载的平面文件。我想要做的是获取文件 [1..N],打开流,然后将它们组合成一个流。所以当file1结束时,我想从file2开始读取,依此类推,直到到达fileN的末尾。
我需要按特定顺序读取这些文件,数据来自一个遗留系统,该系统在 barches 中生成文件,因此一个中的数据依赖于另一个文件中的数据,但我想将它们作为一个连续流处理以简化我的域逻辑接口(interface)。
我四处搜索并找到了 PipedInputStream,但我并不肯定这就是我所需要的。举个例子会很有帮助。
它就在 JDK 中!报价 JavaDoc of SequenceInputStream
:
MỘT SequenceInputStream
represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.
您想连接任意数量的 Dòng đầu vào
,而 SequenceInputStream
只接受两个。但是由于 SequenceInputStream
也是一个 Dòng đầu vào
你可以递归地应用它(嵌套它们):
new SequenceInputStream(
new SequenceInputStream(
new SequenceInputStream(file1, file2),
file3
),
file4
);
...你明白了。
另见
Tôi là một lập trình viên xuất sắc, rất giỏi!