内存直接映射到字符串
我有一个文件通过“FileChannel.map()”映射到内存中。然而,在读取字符串来执行以下操作时似乎有点奇怪:
1) read a int for the string length
2) allocate a byte[length] object
3) use .get to read length bytes
4) convert the byte[] to a string
现在我从我的 C++ 背景知道内存映射文件作为指向内存的指针提供给用户。那么有没有一种好方法可以跳过使用字节数组并让字符串转换直接从映射内存中进行呢?
I have a file I'm mapping into memory via 'FileChannel.map()'. However it seems a bit odd when reading a string to do the following:
1) read a int for the string length
2) allocate a byte[length] object
3) use .get to read length bytes
4) convert the byte[] to a string
Now I know from my C++ background that memory mapped files are given to the user as pointers to memory. So is there a good way to skip using a byte array and just have the string conversion go right off the mapped memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议:
也可以使用mapped.asCharBuffer()并通过这种方式获取字符。
I suggest:
It is also possible to use the mapped.asCharBuffer() and get the chars by this way.
最终,没有。但有一种方法可以将数据视为字符。看看 ByteBuffer.asCharBuffer()。
在内部, asCharBuffer() 方法执行与您提议的相同的操作,但是是在逐个字符的基础上进行的。
Ultimately, no. But there is a way to get a view of the data as characters. Look at ByteBuffer.asCharBuffer().
Internally, the asCharBuffer() method does the same thing you're proposing, but on a char-by-char basis.
String 想要数据的私有副本是不可避免的。字符串是不可变的,如果它使用共享数组,您可能会破坏它。不幸的是,没有
String(CharSequence)
或String(ByteBuffer)
构造函数。There's no getting around String wanting a private copy of the data. Strings are immutable and if it used a shared array, you could break that. It's unfortunate that there's no
String(CharSequence)
orString(ByteBuffer)
constructor.