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

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

问题描述

我想知道是否有任何意识形态方法可以将多个InputStream链接到Java(或Scala)中的一个连续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中!引用 JavaDoc SequenceInputStream

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.

你想要连接任意数量的 InputStream s而 SequenceInputStream 只接受两个。但由于 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
);

...你明白了。

  • How do you merge two input streams in Java? (dup?)

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

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