【发布时间】:2017-07-25 21:38:08
【问题描述】:
我正在考虑使用 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) 失败了。有什么建议吗?
【问题讨论】:
-
你必须输入
0而不是0,因为你的字节数组从零开始 -
另请注意:您将无法在阅读时使用
outputArray.length- 您不知道要分配多少 -
@IlyaBursov 谢谢!对于您的第一点...这是因为我希望字符串成为从 pos 8 开始的第二个字段。对于第二点,我可以指定 MAX_LEN 的上限,我知道我的字符串不会长于那个并且读入那个缓冲区?
-
put的第二个参数在源数组中偏移,而不是在目标缓冲区中 -
@IlyaBursov 我明白了。谢谢。那么在指定位置将字节数组(src)放入当前缓冲区(dst)的建议方法是什么?总是必须调用 mbb.position(index) 来设置它,比如在 8?
标签: java nio bytebuffer mappedbytebuffer