Converting a Java byte reader to an InputStream -
consider generic byte reader implementing following simple api read unspecified number of bytes data structure otherwise inaccessible:
public interface bytereader { public byte[] read() throws ioexception; // returns null @ eof }
how above efficiently converted standard java inputstream, application using methods defined inputstream
class, works expected?
a simple solution subclassing inputstream
to
- call
read()
method ofbytereader
as neededread(...)
methods ofinputstream
- buffer bytes retrieved in byte[] array
- return part of byte array expected, e.g., 1 byte @ time whenever
inputstream read()
method called.
however, requires more work efficient (e.g., avoiding multiple byte array allocations). also, application scale large input sizes, reading memory , processing not option.
any ideas or open source implementations used?
create multiple bytearrayinputstream
instances around returned arrays , use them in stream provides concatenation. instance use sequenceinputstream
this.
trick implement enumeration<bytearrayinputstream>
can use bytereader
class.
edit: i've implemented answer, better create own inputstream
instance instead. unfortunately, solution not let handle ioexception
gracefully.
final enumeration<bytearrayinputstream> basenum = new enumeration<bytearrayinputstream>() { bytearrayinputstream baos; boolean ended; @override public boolean hasmoreelements() { if (ended) { return false; } if (baos == null) { getnextba(); if (ended) { return false; } } return true; } @override public bytearrayinputstream nextelement() { if (ended) { throw new nosuchelementexception(); } if (baos.available() != 0) { return baos; } getnextba(); return baos; } private void getnextba() { byte[] next; try { next = bytereader.read(); } catch (ioexception e) { throw new illegalstateexception("issues reading byte arrays"); } if (next == null) { ended = true; return; } this.baos = new bytearrayinputstream(next); } }; sequenceinputstream sis = new sequenceinputstream(basenum);
Comments
Post a Comment