开发者

Any know of a ByteArrayOutputStream that includes a InputStream getter?

开发者 https://www.devze.com 2023-02-07 01:00 出处:网络
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 ge

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 ;-) )

0

精彩评论

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

关注公众号