我想使用MappedByteBuffer存储/加载一些数据到文件。假设我有长度为A的字段A,字符串的字段B在序列化时如下所示: A(long)| B(字符串)IndexOutOfBoundsException当使用MappedByteBuffer
现在我想写和读它。这里是一段示例代码:
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)
和mbb.get(outputArray,8,outputArray.length)
检索长,但现在我没有在地方(2)。有什么建议么?
而不是'8'你必须把0放在你的字节数组从零开始 –
也注意:你不能像使用outputArray.length一样读你不知道多少分配 –
@IlyaBursov谢谢!对于你的第一点......这是因为我希望字符串成为从第8点开始的第2个字段,对于第2点,我可以指定MAX_LEN的上限,我知道我的字符串不会长于读入该缓冲区? – stranger