Any know of a ByteArrayOutputStream that includes a InputStream getter?
Many times after filling up a ByteArrayOutputStream with bytes and then create开发者_如何学编程 an InputStream. However it seems a bit dumb that to do all that copying. Ideally once the InputStream getter is called a flag should be set in the ByteArrayOutputStream so writes will fail.
It's pretty easy to write:
public class ThinkOfADecentName extends ByteArrayOutputStream
{
public ByteArrayInputStream createInputStream()
{
// Uses protected fields
return new ByteArrayInputStream(buf, 0, count);
}
}
Note that any further writes to the ByteArrayOutputStream may or may not be reflected in the input stream, based on whether reallocation occurs and the position being written. Basically I'd only call this after finishing writing :)
Is there really a need? An input stream for some bytes is a one liner:
InputStream in = new ByteArrayInputStream(
new ByteArrayOutputStream(bytes).toByteArray()));
(With Jon's solution you don't create a new byte array internally, so this one liner might be a bit slower and uses some extra memeory. The advantage: we don't have to invent a class name ;-) )
精彩评论