3

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?

1
  • That's to be determined at this point. Currently it's ASCII. Commented Apr 29, 2011 at 19:54

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

To prevent the unnecessary copy to a buffer, this is the way to do it. Of course, making a string still involves a copy, as rlibby mentioned.
...so that he can get an UnsupportedOperationException? MappedByteBuffer is not backed by an array, MappedByteBuffer.hasArray() returns false, and MappedByteBuffer.array() throws the above exception.
It could be true, so, he will need to use asCharBuffer() and read each char to another buffer and so on construct the string.
3

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.

1 Comment

+1 that is the best he could possibly hope for, if the file is ASCII, because Java strings are Unicode..
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.