How does .array () not work on ByteBuffers returned from map'ed FileChannels?

I am doing memory mapping IO in Java. The FileChannel class allows you to map a ByteBuffer to a specific part of a file. I do this when the file is open read-only.

The problem I am facing is that I get an exception when I try to call the .array () method on the received ByteBuffer. Perhaps this is because .array () returns a byte [] array, and I really need a finalized byte array?

Is there any way around this?

+4
source share
1 answer

I'm going to assume that this is a FileChannel.map method that can map a file into memory, which can be accessed by MappedByteBuffer .

In the documentation for the FileChannel.map method, if the file appears as read-only, any attempt to change the buffer will result in ReadOnlyBufferException :

A file area can be displayed in memory in one of three modes:

  • Read Only: Any attempt to modify the received buffer will raise a ReadOnlyBufferException . ( MapMode.READ_ONLY )

In terms of exceptions thrown by ByteBuffer.array , there are two types of exceptions that are thrown depending on the cause of the problem:

Throws:

  • ReadOnlyBufferException - If this buffer is supported by the array but is read-only
  • UnsupportedOperationException - If this buffer is not supported by the available array

Although the thrown exception is not mentioned in the question, it is possible that a read-only file raises a ReadOnlyBufferException thrown by the array method.

In addition, it should also be mentioned that the ByteBuffer.array method is an optional operation:

Returns an array of bytes that supports this buffer (optional operation).

To make sure the array method returns a byte[] that you can use, call the hasArray method, as suggested in the documentation for the array method:

Call the hasArray method before invoking this method to make sure that this buffer has an available support array.

+3
source

All Articles