Reputation: 10653
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?
Upvotes: 3
Views: 1889
Reputation: 2278
I suggest:
MappedByteBuffer mapped = fileChannel.map(mode, position, size);
String s = new String(mapped.array());
It is also possible to use the mapped.asCharBuffer() and get the chars by this way.
Upvotes: 3
Reputation: 6021
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)
or String(ByteBuffer)
constructor.
Upvotes: 1
Reputation: 15789
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.
Upvotes: 3