我正在考虑使用 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/