Reputation: 69
I have situation where I need to merge multiple InputStream into single stream. I tried below code but it only return content from last file / stream. what is wrong with code? And is there a better way to merge multiple streams?
def mergeInputStreams(l: List[File], accum: SequenceInputStream): SequenceInputStream = l match {
case Nil => accum
case x :: xs =>
val is = new FileInputStream(x.pathAsString)
mergeInputStreams(xs, new SequenceInputStream(is, accum))
}
Upvotes: 0
Views: 852
Reputation: 11607
You're on the right track, but I would use SequenceInputStream
's constructor that takes an Enumeration
of File
s and just map my input list of files into the right types to feed that:
import java.io.{File, FileInputStream, InputStream, SequenceInputStream}
import scala.collection.JavaConverters.asJavaEnumeration
def mergeInputStreams(files: Iterator[File]): InputStream =
new SequenceInputStream(asJavaEnumeration(files.map(new FileInputStream(_))))
The other trick is to use Scala's included conversion method to convert from a Scala Iterator
to a Java Enumeration
. The conversion preserves the ordering and the fact that it's a traversal over a sequence of files, so it also preserves the input stream concatenation.
Upvotes: 2