gpt4 book ai didi

java - 如何将多个不同的 InputStream 链接到一个 InputStream

转载 作者:IT老高 更新时间:2023-10-28 20:24:11 26 4
gpt4 key购买 nike

我想知道是否有任何理想的方式可以将多个 InputStream 链接到 Java(或 Scala)中的一个连续 InputStream 中。

我需要它来解析我从 FTP 服务器通过网络加载的平面文件。我想要做的是获取文件 [1..N],打开流,然后将它们组合成一个流。所以当file1结束时,我想从file2开始读取,依此类推,直到到达fileN的末尾。

我需要按特定顺序读取这些文件,数据来自一个遗留系统,该系统在 barches 中生成文件,因此一个中的数据依赖于另一个文件中的数据,但我想将它们作为一个连续流处理以简化我的域逻辑接口(interface)。

我四处搜索并找到了 PipedInputStream,但我并不肯定这就是我所需要的。举个例子会很有帮助。

最佳答案

它就在 JDK 中!报价 JavaDoc of SequenceInputStream :

A 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.

您想连接任意数量的 InputStream,而 SequenceInputStream 只接受两个。但是由于 SequenceInputStream 也是一个 InputStream 你可以递归地应用它(嵌套它们):

new SequenceInputStream(
new SequenceInputStream(
new SequenceInputStream(file1, file2),
file3
),
file4
);

...你明白了。

另见

关于java - 如何将多个不同的 InputStream 链接到一个 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14295099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com