我正在考虑使用MappedByteBuffer将一些数据存储/加载到一个文件中。让我们假设我的字段A类型为long,字符串的字段B在序列化时如下所示: A(long) x- B( string )
现在我想写和读给它听。下面是一段示例代码:
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)
但现在我在地方上失败了。有什么建议吗?
发布于 2017-07-25 21:46:13
试一试
mbb.put(destArray, 0, sourceArray.length)我不认为您想要开始以8字节的偏移量写入,否则您将尝试在数组的长度上写入8个字节。
https://stackoverflow.com/questions/45313930
复制相似问题