I have a byte array and it has to be converted to MappedByteBuffer.
But when I try creating MappedByteBuffer, an error occurs.
error: cannot find symbol method MappedByteBuffer(int,int,int,int,byte[],int)
MappedByteBuffer.java
package java.nio;
import java.io.FileDescriptor;
import sun.misc.Unsafe;
public abstract class MappedByteBuffer
extends ByteBuffer
{
...
// Android-added: Additional constructor for use by Android's DirectByteBuffer.
MappedByteBuffer(int mark, int pos, int lim, int cap, byte[] buf, int offset) {
super(mark, pos, lim, cap, buf, offset); // <- when I hover mouse here, ByteBuffer() in ByteBuffer cannot be applied to message appears with a red underline.
this.fd = null;
}
...
}
ByteBuffer.java
package java.nio;
import libcore.io.Memory;
import dalvik.annotation.codegen.CovariantReturnType;
public abstract class ByteBuffer
extends Buffer
implements Comparable<ByteBuffer>
{
// These fields are declared here rather than in Heap-X-Buffer in order to
// reduce the number of virtual method invocations needed to access these
// values, which is especially costly when coding small buffers.
//
final byte[] hb; // Non-null only for heap buffers
final int offset;
boolean isReadOnly; // Valid only for heap buffers
// Creates a new buffer with the given mark, position, limit, capacity,
// backing array, and array offset
//
ByteBuffer(int mark, int pos, int lim, int cap, // package-private
byte[] hb, int offset)
{
// Android-added: elementSizeShift parameter (log2 of element size).
super(mark, pos, lim, cap, 0 /* elementSizeShift */);
this.hb = hb;
this.offset = offset;
}
...
}
What I think strange is when goto definition of extends ByteBuffer
in MappedByteBuffer.java, it shows ByteBuffer.annotated.java, not ByteBuffer.java
ByteBuffer.annotated.java
// -- This file was mechanically generated: Do not edit! -- //
package java.nio;
@SuppressWarnings({"unchecked", "deprecation", "all"})
public abstract class ByteBuffer extends java.nio.Buffer implements java.lang.Comparable<java.nio.ByteBuffer> {
ByteBuffer(int mark, int pos, int lim, int cap) { super(0, 0, 0, 0, 0); throw new RuntimeException("Stub!"); }
I don't know what {classname}.annotated.java does, so it might not be an error, but I pasted because I think it's odd.
So how can I create MappedByteBuffer from byte array? There is only 1 constructor, but it's broken.
There is only 1 constructor, but it's broken
That constructor isn't public (it's package-private), so you can't call it.
So how can I create MappedByteBuffer from byte array?
You can't, not without writing it to a file first. From the docs:
A direct byte buffer whose content is a memory-mapped region of a file.
If you do need to create a MappedByteBuffer
specifically and not just a ByteBuffer
from a byte array, you need to write it to a file and use FileChannel.map
. If you just need a ByteBuffer
, you can use ByteBuffer.wrap