gpt4 book ai didi

java - 使用 ByteBuffer 处理 byte[]

转载 作者:行者123 更新时间:2023-12-02 00:47:04 25 4
gpt4 key购买 nike

我尝试通过 ByteBuffer 访问 byte[] 以表示我定义的文件类型。 byte[] 中的第一个位置包含一些元数据并通过位操作进行处理。所以它们根本不代表字符。

我想在某个固定位置添加文件数据(例如字符)。

byte[] file_portion 包含大文件的一部分:开始部分。其中包括带有元数据的 header 。content 是一个字符串,其中包含我想要添加到该缓冲区的信息。 start_pos 是保存内容中新文件数据的第一个位置。

ByteBuffer my_content = ByteBuffer.allocate(this.file_portion.length);
content_buffer.wrap(this.file_portion);

for (int i = 0; i < content.length(); i++) {
char tmp = content.toCharArray()[i];
my_content.put(this.start_pos + i, (byte) tmp)
}

如果我重新映射它,我会得到垃圾和空虚:

CharBuffer debug = my_content.asCharBuffer();
System.out.println("debug " + debug);

我可以理解第一个位置是否显示损坏的字符...但没有一个位置是正确的。

最佳答案

如果您要向 ByteBuffer 添加字符并期望它们可以通过 CharBuffer View 读取,则应该使用 putChar(...) 而不是 put(...)。

已编辑:根据OP评论。

例如:

char[] chars = content.toCharArray();  // removed from loop per leonbloy's excellent comment  
CharBuffer cbuf = my_content.asCharBuffer();

for (int i = 0; i < content.length(); i++) {
cbuf.putChar(chars[i]);
}

CharBuffer debug = my_content.asCharBuffer();
System.out.println(debug);

my_content.position(my_content.position() + 2*chars.length);

否则 CharBuffer 将读取两个连续字节作为单个字符。现在,cbuf 缓冲区将在字节缓冲区停止的同一点开始加载字符。加载所有字符后,原始 ByteBuffer 将被定位到下一个位置。希望这就是您正在寻找的内容。

关于java - 使用 ByteBuffer 处理 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4685271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com