开发者

Pipe or Swap Input / Output Streams in Java

A list of analyser classes which analyse a InputStream for dependencies, changes a few things and write it to an OutputStream:

public Set<Dependency> analyse(InputStream i, OutputS开发者_C百科tream o);

The analysers should be chained like:

for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(in, out));
 in = new ByteArrayInputStream(out.toByteArray());
} 

Now I'm working in a environment where in is final.

  1. Is there a better way to "chain" the streams?
  2. Is the "swap" operation from "out" to "in" with ByteArrayInputStream expensive?
  3. How to deal with the problem that "in" is final?


  1. Use helper threads and java.io.PipedInputStream/java.io.PipedOutputStream pairs.
  2. Probably it will not perform well on big streams.
  3. As it is said in another response, use a local non-final variable to do the chaining

Note that by applying 1. you do not need to worry about 2 because you are in fact piping the streams.


For question 2.
I would provide my own subclass that has a direct access to ByteArrayInputStream's and ByteArrayOutputStream's buffer. That way you don't waist memory and time by making extra copy in toByteArray.

For question 3.
Assign it to a local non-final variable,

InputStream nonFinalIn = in;
for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(nonFinalIn, out));
 nonFinalIn = new ByteArrayInputStream(out.toByteArray());
}

Beware, though, that the original in will no longer be valid ( it will be at the end-of-stream )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜