In Java I need to put content of OutputStream (I fill data to that stream myself) into a ByteBuffer. How to do it in a simple way ?
A:
Why would you want to put it in a buffer AFTER you put the data in the outputstream? The way you read it back is usually by a inputstream that reads from the source where you wrote it in which case you just read it to a bytearray. Correct me if I'm wrong.
Jonas B
2010-04-26 20:29:47
You are right. However my question does make very much of a sense. I need to do this to link 2 different frameworks: one of them that can only write data into OutputStream and one of them can only read from ByteBuffer. There is a way to put it into memory stream and than read it into buffer but I don't like this...
drasto
2010-04-26 20:44:58
+1
A:
Try using PipedOutputStream instead of OutputStream. You can then connect a PipedInputStream to read the data back out of the PipedOutputStream.
Marcus Adams
2010-04-26 20:53:24
Looks fine. Similar think can be done with ByteArrayOutputStream by calling its method newInputStream. However there is more strightforward solution - to wrap array that backs up ByteArrayOutputStream into ByteBuffer directly. That is what I've done.
drasto
2010-04-26 21:12:03
+3
A:
You can create a ByteArrayOutputStream and write to it, and extract the contents as a byte[] using toByteArray(). Then ByteBuffer.wrap(byte []) will create a ByteBuffer with the contents of the output byte array.
DJClayworth
2010-04-26 21:02:45
That is exactly what I've done just before I've read your comment. So I can approve that this works :))
drasto
2010-04-26 21:08:28