如何将多个不同的 InputStream 链接成一个 InputStream [英] How to chain multiple different InputStreams into one InputStream

查看:51
本文介绍了如何将多个不同的 InputStream 链接成一个 InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 Java(或 Scala)中是否有任何思想方法可以将多个 InputStream 链接成一个连续的 InputStream.

I'm wondering if there is any ideomatic way to chain multiple InputStreams into one continual InputStream in Java (or Scala).

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

What I need it for is to parse flat files that I load over the network from an FTP-Server. What I want to do is to take file[1..N], open up streams and then combine them into one stream. So when file1 comes to an end, I want to start reading from file2 and so on, until I reach the end of fileN.

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

I need to read these files in a specific order, data comes from a legacy system that produces files in barches so data in one depends on data in another file, but I would like to handle them as one continual stream to simplify my domain logic interface.

我四处寻找并找到了 PipedInputStream,但我不确定这就是我所需要的.举个例子会有帮助.

I searched around and found PipedInputStream, but I'm not positive that is what I need. An example would be helpful.

推荐答案

它就在 JDK 中!引用 SequenceInputStream 的 JavaDoc:

It's right there in JDK! Quoting JavaDoc of SequenceInputStream:

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

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

You want to concatenate arbitrary number of InputStreams while SequenceInputStream accepts only two. But since SequenceInputStream is also an InputStream you can apply it recursively (nest them):

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

...你懂的.

这篇关于如何将多个不同的 InputStream 链接成一个 InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆