gpt4 book ai didi

java - 使用 MappedByteBuffer 时出现 IndexOutOfBoundsException

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

我正在考虑使用 MappedByteBuffer 将一些数据存储/加载到文件中。假设我有 long 类型的字段 A 和字符串的字段 B,序列化时如下所示:A(长)| B(字符串)

现在我想写入和读取它。这是一段示例代码:

RandomAccessFile file = new RandomAccessFile(dataPath.toString(), "rw");
MappedByteBuffer mbb = file.getChannel().map(FileChannel.MapMode
.READ_WRITE, 0, 256);
long num = 500;
mbb.putLong(0, num); // (1) first write the long value at beginning
String str = "Hello World!";
byte[] input = str.getBytes();
//then write a string
mbb.put(input, 8, input.length); // (2) IndexOutOfBoundsException

所以稍后我可以通过调用 mbb.getLong(0) 来检索 long
mbb.get(outputArray,8,outputArray.length)

但现在我在第 (2) 处失败了。有什么建议吗?

最佳答案

尝试

mbb.put(destArray, 0, sourceArray.length)

我认为您不想从 8 字节偏移量开始写入,否则您会尝试在数组长度上写入 8 字节。

关于java - 使用 MappedByteBuffer 时出现 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313930/

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