如何将 ByteBuffer 的内容放入 OutputStream 中?

发布于 2024-07-13 21:39:01 字数 299 浏览 6 评论 0原文

我需要将 java.nio.ByteBuffer 的内容放入 java.io.OutputStream 中。 (希望我有一个Channel,但我没有)最好的方法是什么?

我无法使用 ByteBuffer 的 array() 方法,因为它可以是只读缓冲区。

我还可能会在使用此 ByteBuffer 和拥有常规的 byte[] 数组之间散布对 OutputStream 的写入,我可以直接使用 OutputStream.write()

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月苍老的讽刺 2024-07-20 21:39:01

查看 Channels.newChannel(OutputStream)。 它会给你一个给定输出流的通道。 使用 WritableByteChannel 适配器,您可以提供 ByteBuffer,它将其写入 OutputStream。

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

   channel.write(buffer);
}

这应该可以解决问题!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文