【问题标题】:Why can't I add a String to a ByteBuffer?为什么我不能将字符串添加到 ByteBuffer?
【发布时间】:2014-07-31 05:47:55
【问题描述】:

当我尝试将字符串添加到字节缓冲区时,它不会写入文件中。虽然我尝试添加 int 和 double 它工作正常。但是对于字符串它不起作用。

buffer.asCharBuffer().put(value.getValue1());
buffer.asCharBuffer().put(value.getValue2());

【问题讨论】:

  • 请添加一些上下文。什么文件? value.getValueX() 是什么? buffer 是什么?你想做什么?
  • 然后定义不工作。你认为它应该做什么,为什么?它做了什么?

标签: java bytebuffer


【解决方案1】:
  1. 分配一个新的ByteBuffer 并将其大小设置为足够大的数字,以避免在向其放入字节时缓冲区溢出
  2. 使用asCharBuffer() API 方法可以直接将字符放入字节缓冲区中
  3. 使用put(String) API 方法,我们可以将字符串直接放入字节缓冲区

  4. toString() API 方法返回ByteBuffer 内容的字符串表示形式。不要忘记flip()ByteBuffer,因为toString() API 方法会从当前缓冲区的位置向前显示ByteBuffer 的内容:

UseByteBufferToStoreStrings:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class UseByteBufferToStoreStrings {

    public static void main(String[] args) {

        // Allocate a new non-direct byte buffer with a 50 byte capacity


    // set this to a big value to avoid BufferOverflowException
        ByteBuffer buf = ByteBuffer.allocate(50); 

        // Creates a view of this byte buffer as a char buffer
        CharBuffer cbuf = buf.asCharBuffer();

        // Write a string to char buffer
        cbuf.put("Your sting");

        // Flips this buffer.  The limit is set to the current position and then
        // the position is set to zero.  If the mark is defined then it is discarded
        cbuf.flip();

        String s = cbuf.toString();  // a string

        System.out.println(s);

    }

}

read more...

【讨论】:

  • 你没有解决 OP 的问题。
【解决方案2】:

如果您想使用 getBytes() 方法的返回值将 String 添加到 ByteBuffer 中。

buf.put("Your string".getBytes); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2014-10-10
    • 2021-10-22
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多