Java 如何将 ByteBuffer 的内容放入 OutputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/579600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put the content of a ByteBuffer into an OutputStream?
提问by Jason S
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?
我需要将 a 的内容java.nio.ByteBuffer
放入java.io.OutputStream
. (希望我有一个,Channel
但我没有)这样做的最佳方法是什么?
I can't use the ByteBuffer's array()
method since it can be a read-only buffer.
我不能使用 ByteBuffer 的array()
方法,因为它可以是只读缓冲区。
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.
我也可能在使用这个 ByteBuffer 和拥有一个byte[]
我可以OutputStream.write()
直接使用的常规数组之间穿插写入 OutputStream 。
采纳答案by ng.
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.
看看Channels.newChannel(OutputStream)。它会给你一个给定 OutputStream 的通道。使用 WritableByteChannel 适配器,您可以提供将其写入 OutputStream 的 ByteBuffer。
public void writeBuffer(ByteBuffer buffer, OutputStream stream) {
WritableByteChannel channel = Channels.newChannel(stream);
channel.write(buffer);
}
This should do the trick!
这应该可以解决问题!