Search code examples
javaniorandomaccessfilemappedbytebuffer

Type of position in RandomAccessFile is long but it is int in MappedByteBuffer


The RandomAccessFile class in Java uses type long in methods getFilePointer(), length(), seek(), and setLength().

However, if I want to manipulate this file via MappedByteBuffer, I can only specify the Buffer's position as an int.

Is this a feature or an API shortcoming in JDK? (Very likely, it's the former but not sure why.)

Is downcasting the file pointer from long to an int Buffer position the only way around?


Solution

  • The FileChannel.map call which creates the mapping has long size but the Javadoc says:

    The size of the region to be mapped; must be non-negative and no greater than Integer.MAX_VALUE

    So an int value is sufficent to set the position inside the map.

    For Java 22 onwards the Foreign Functions and Memory support adds an alternative version of FileChannel.map which returns a MemorySegment which doesn't have the size restriction.