Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory map directly to string

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?

like image 949
Timothy Baldridge Avatar asked Mar 08 '26 00:03

Timothy Baldridge


1 Answers

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.

like image 163
Pih Avatar answered Mar 10 '26 12:03

Pih