3

我有一个文件通过“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++ 背景中知道,内存映射文件作为指向内存的指针提供给用户。那么有没有一种很好的方法来跳过使用字节数组而让字符串转换直接离开映射的内存?

4

3 回答 3

4

我建议:

MappedByteBuffer mapped = fileChannel.map(mode, position, size);
String s = new String(mapped.array());

也可以使用 mapped.asCharBuffer() 并通过这种方式获取字符。

于 2011-04-29T20:00:38.523 回答
3

最终,没有。但是有一种方法可以将数据视为字符。查看 ByteBuffer.asCharBuffer()。

在内部, asCharBuffer() 方法执行您提议的相同操作,但以逐个字符为基础。

于 2011-04-29T19:50:40.767 回答
1

没有绕过 String 想要数据的私有副本。字符串是不可变的,如果它使用共享数组,你可以打破它。不幸的是没有String(CharSequence)String(ByteBuffer)构造函数。

于 2011-04-29T19:50:56.440 回答