Search code examples
javacopyslicebytebufferunsupportedoperation

How to copy partially one byteBuffer to another one without byteBuffer.array()


I have an empty byteBuffer allocated as

data = ByteBuffer.allocateDirect(layerSize(0, faces - 1, 0, levels - 1) * layers);

Following this answer, I tried to use the array() method as following

public void setData(ByteBuffer data, int layer, int face, int level) {
    int offset = offset(layer, face, level);
    int levelSize = levelSize(level);
    this.data.put(data.array(), offset, levelSize);
}

But I get:

Caused by: java.lang.UnsupportedOperationException
    at java.nio.ByteBuffer.array(ByteBuffer.java:994)

The source bytebuffer I am trying to use is read in this way:

    File file = new File(Load.class.getResource(fileName).getFile());
    FileInputStream fileInputStream = new FileInputStream(file);
    FileChannel fileChannel = fileInputStream.getChannel();

    return loadKtx(fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) file.length()));

public static Texture loadKtx(ByteBuffer byteBuffer) throws IOException {
    ...
                byteBuffer.position(offset);
                byteBuffer.limit(offset + faceSize);

                ByteBuffer data = byteBuffer.slice();
                texture.setData(data, layer, face, level);

                byteBuffer.position(0);
                byteBuffer.limit(byteBuffer.capacity());

Is there a better option than a simple

    for (int b = 0; b < levelSize; b++) {
        this.data.put(offset + b, data.get(b));
    }

?

However, whole project here for who is interested.


Solution

  • Unfortunately it looks like there is not.

    Credits to @Stefen C