Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put the content of a ByteBuffer into an OutputStream?

I need to put the contents of a java.nio.ByteBuffer into an java.io.OutputStream. (wish I had a Channel instead but I don't) What's the best way to do this?

I can't use the ByteBuffer's array() method since it can be a read-only buffer.

I also may be interspersing writes to the OutputStream between using this ByteBuffer and having a regular array of byte[] which I can with use OutputStream.write() directly.

like image 674
Jason S Avatar asked Feb 23 '09 22:02

Jason S


People also ask

How do I write ByteBuffer to a file?

To write data into a FileChannel or read from it, you need a ByteBuffer . Data is put into the ByteBuffer with put() and then written from the buffer to the file with FileChannel. write(buffer) . FileChannel.

How do you write a string to OutputStream?

Streams ( InputStream and OutputStream ) transfer binary data. If you want to write a string to a stream, you must first convert it to bytes, or in other words encode it. You can do that manually (as you suggest) using the String. getBytes(Charset) method, but you should avoid the String.


1 Answers

Look at Channels.newChannel(OutputStream). It will give you a channel given an OutputStream. With the WritableByteChannel adapter you can provide the ByteBuffer which will write it to the OutputStream.

public void writeBuffer(ByteBuffer buffer, OutputStream stream) {    WritableByteChannel channel = Channels.newChannel(stream);     channel.write(buffer); } 

This should do the trick!

like image 110
ng. Avatar answered Sep 21 '22 07:09

ng.