Java : MappedByteBuffer con ejemplos

MappedByteBuffer (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará muestras de código para la mayoría de los métodos MappedByteBuffer.

Nota :


Summary

Un búfer de bytes directo cuyo contenido es una región mapeada en memoria de un archivo. (Traducción automática)

Class diagram

public MappedByteBuffer createBuffer(Path file) throws IOException {
    try (final var channel = FileChannel.open(file,
            StandardOpenOption.READ, StandardOpenOption.WRITE)) {

        return channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
    }
}
final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

final var buffer = createBuffer(file);

{
    final var dst = new byte[buffer.capacity()];
    buffer.get(0, dst);
    System.out.println(Arrays.toString(dst)); // [10, 20, 30, 40, 50]

    final var ret = Files.readAllBytes(file);
    System.out.println(Arrays.toString(ret)); // [10, 20, 30, 40, 50]
}

buffer.put(0, (byte) -10);
buffer.put(1, (byte) -20);
buffer.put(2, (byte) -30);

{
    final var dst = new byte[buffer.capacity()];
    buffer.get(0, dst);
    System.out.println(Arrays.toString(dst)); // [-10, -20, -30, 40, 50]

    final var ret = Files.readAllBytes(file);
    System.out.println(Arrays.toString(ret)); // [-10, -20, -30, 40, 50]
}
final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file,
        StandardOpenOption.READ, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(
            FileChannel.MapMode.READ_ONLY, 0, channel.size());

    {
        final var dst = new byte[buffer.capacity()];
        buffer.get(0, dst);
        System.out.println(Arrays.toString(dst)); // [10, 20, 30, 40, 50]

        final var ret = Files.readAllBytes(file);
        System.out.println(Arrays.toString(ret)); // [10, 20, 30, 40, 50]
    }

    final var src = ByteBuffer.allocate(3)
            .put((byte) -10)
            .put((byte) -20)
            .put((byte) -30)
            .clear();

    System.out.println(channel.write(src)); // 3

    {
        final var dst = new byte[buffer.capacity()];
        buffer.get(0, dst);
        System.out.println(Arrays.toString(dst)); // [-10, -20, -30, 40, 50]

        final var ret = Files.readAllBytes(file);
        System.out.println(Arrays.toString(ret)); // [-10, -20, -30, 40, 50]
    }
}

Methods

final MappedByteBuffer clear ()

Borra este buffer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    buffer.position(2);
    buffer.limit(4);

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=2 lim=4 cap=5]

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.hasRemaining()); // false

    System.out.println(buffer.clear()); // java.nio.DirectByteBufferR[pos=0 lim=5 cap=5]

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50
    System.out.println(buffer.hasRemaining()); // false
}

abstract MappedByteBuffer compact ()

Compacta este buffer (operación opcional). (Traducción automática)

final var file = Path.of("R:", "java-work", "test1.data");
System.out.println(file); // R:\java-work\test1.data

final byte[] bytes = {10, 20, 30, 40, 50, 60};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file,
        StandardOpenOption.READ, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
    buffer.position(3);
    System.out.println(buffer.compact()); // java.nio.DirectByteBuffer[pos=3 lim=6 cap=6]
}

final var ret = Files.readAllBytes(file);
System.out.println(Arrays.toString(ret)); // [40, 50, 60, 40, 50, 60]
final var file = Path.of("R:", "java-work", "test2.data");
System.out.println(file); // R:\java-work\test2.data

final byte[] bytes = {10, 20, 30, 40, 50, 60};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file,
        StandardOpenOption.READ, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());

    buffer.position(2);
    System.out.println(buffer.compact()); // java.nio.DirectByteBuffer[pos=4 lim=6 cap=6]
}

final var ret = Files.readAllBytes(file);
System.out.println(Arrays.toString(ret)); // [30, 40, 50, 60, 50, 60]
final var file = Path.of("R:", "java-work", "test3.data");
System.out.println(file); // R:\java-work\test3.data

final byte[] bytes = {10, 20, 30, 40, 50, 60};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file,
        StandardOpenOption.READ, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());

    buffer.position(4);
    System.out.println(buffer.compact()); // java.nio.DirectByteBuffer[pos=2 lim=6 cap=6]
}

final var ret = Files.readAllBytes(file);
System.out.println(Arrays.toString(ret)); // [50, 60, 30, 40, 50, 60]

abstract MappedByteBuffer duplicate ()

Crea un nuevo búfer de bytes que comparte el contenido de este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    buffer.position(1);
    buffer.limit(4);

    final var duplicated = buffer.duplicate();

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=1 lim=4 cap=5]
    System.out.println(duplicated); // java.nio.DirectByteBufferR[pos=1 lim=4 cap=5]

    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40

    System.out.println(duplicated.get()); // 20
    System.out.println(duplicated.get()); // 30
    System.out.println(duplicated.get()); // 40
}

final MappedByteBuffer flip ()

Voltea este buffer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=3 lim=5 cap=5]
    System.out.println(buffer.flip()); // java.nio.DirectByteBufferR[pos=0 lim=3 cap=5]

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30
}

final MappedByteBuffer force ()

Fuerza a que cualquier cambio realizado al contenido de este búfer se escriba en el dispositivo de almacenamiento que contiene el archivo mapeado. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

try (final var channel = FileChannel.open(file, StandardOpenOption.READ,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 3);

    {
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [0, 0, 0]
    }

    buffer.put((byte) 10);
    buffer.put((byte) 20);
    buffer.put((byte) 30);

    {
        // NOTE : In my environment, writing to the file is completed
        // before the force method is called.
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
    }

    final var ret = buffer.force();
    System.out.println(buffer.equals(ret)); // true

    {
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
    }
}

final MappedByteBuffer force (int index, int length)

Fuerza a que cualquier cambio realizado en una región del contenido de este búfer se escriba en el dispositivo de almacenamiento que contiene el archivo mapeado. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

try (final var channel = FileChannel.open(file, StandardOpenOption.READ,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);

    {
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [0, 0, 0, 0, 0]
    }

    buffer.put((byte) 10);
    buffer.put((byte) 20);
    buffer.put((byte) 30);

    {
        // NOTE : In my environment, writing to the file is completed
        // before the force method is called.
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [10, 20, 30, 0, 0]
    }

    final var pos = buffer.position();
    System.out.println(pos); // 3

    final var ret = buffer.force(0, pos);
    System.out.println(buffer.equals(ret)); // true

    {
        final var bytes = Files.readAllBytes(file);
        System.out.println(Arrays.toString(bytes)); // [10, 20, 30, 0, 0]
    }
}

final boolean isLoaded ()

Indica si el contenido de este búfer reside o no en la memoria física. (Traducción automática)

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.isLoaded()); // false

    final var ret = buffer.load();
    System.out.println(buffer.equals(ret)); // true

    // The isLoaded method always returns false on Windows ...?
    System.out.println(buffer.isLoaded()); // false
}

final MappedByteBuffer limit (int newLimit)

Establece el límite de este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test1.data");
System.out.println(file); // R:\java-work\test1.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=0 lim=5 cap=5]
    System.out.println(buffer.limit()); // 5

    System.out.println(buffer.limit(3)); // java.nio.DirectByteBufferR[pos=0 lim=3 cap=5]
    System.out.println(buffer.limit()); // 3

    System.out.println(buffer.clear()); // java.nio.DirectByteBufferR[pos=0 lim=5 cap=5]
    System.out.println(buffer.limit()); // 5
}
final var file = Path.of("R:", "java-work", "test2.data");
System.out.println(file); // R:\java-work\test2.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.limit(3)); // java.nio.DirectByteBufferR[pos=0 lim=3 cap=5]

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30

    try {
        var _ = buffer.get();
    } catch (BufferUnderflowException e) {
        System.out.println("BufferUnderflowException!");
    }

    // Result
    // ↓
    //BufferUnderflowException!
}

final MappedByteBuffer load ()

Carga el contenido de este buffer en la memoria física. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    {
        // NOTE : In my environment, reading from the file is completed
        // before the load method is called.
        final var dst = new byte[buffer.capacity()];
        buffer.get(0, dst);
        System.out.println(Arrays.toString(dst)); // [10, 20, 30, 40, 50]
    }

    final var ret = buffer.load();
    System.out.println(buffer.equals(ret)); // true

    {
        final var dst = new byte[buffer.capacity()];
        buffer.get(0, dst);
        System.out.println(Arrays.toString(dst)); // [10, 20, 30, 40, 50]
    }
}

final MappedByteBuffer mark ()

Establece la marca de este búfer en su posición. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20

    System.out.println(buffer.position()); // 2
    System.out.println(buffer.mark()); // java.nio.DirectByteBufferR[pos=2 lim=5 cap=5]

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50

    System.out.println(buffer.position()); // 5
    System.out.println(buffer.reset()); // java.nio.DirectByteBufferR[pos=2 lim=5 cap=5]

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50
}

final MappedByteBuffer position (int newPosition)

Establece la posición de este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.position()); // 0

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.position()); // 1

    System.out.println(buffer.get()); // 20
    System.out.println(buffer.position()); // 2

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.position()); // 3

    System.out.println(buffer.get()); // 40
    System.out.println(buffer.position()); // 4

    System.out.println(buffer.get()); // 50
    System.out.println(buffer.position()); // 5

    // java.nio.DirectByteBufferR[pos=3 lim=5 cap=5]
    System.out.println(buffer.position(3));

    System.out.println(buffer.get()); // 40
    System.out.println(buffer.position()); // 4

    System.out.println(buffer.get()); // 50
    System.out.println(buffer.position()); // 5
}

final MappedByteBuffer reset ()

Restablece la posición de este búfer a la posición marcada previamente. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20

    System.out.println(buffer.position()); // 2
    System.out.println(buffer.mark()); // java.nio.DirectByteBufferR[pos=2 lim=5 cap=5]

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50

    System.out.println(buffer.position()); // 5
    System.out.println(buffer.reset()); // java.nio.DirectByteBufferR[pos=2 lim=5 cap=5]

    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50
}

final MappedByteBuffer rewind ()

Rebobina este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    buffer.position(2);
    buffer.limit(4);

    System.out.println(buffer.position()); // 2
    System.out.println(buffer.limit()); // 4

    System.out.println(buffer.rewind()); // java.nio.DirectByteBufferR[pos=0 lim=4 cap=5]

    System.out.println(buffer.position()); // 0
    System.out.println(buffer.limit()); // 4
}

abstract MappedByteBuffer slice ()

Crea un nuevo búfer de bytes cuyo contenido es una subsecuencia compartida del contenido de este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    buffer.position(1);
    buffer.limit(4);

    final var sliced = buffer.slice();

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=1 lim=4 cap=5]
    System.out.println(sliced); // java.nio.DirectByteBufferR[pos=0 lim=3 cap=3]

    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.hasRemaining()); // false

    System.out.println(sliced.get()); // 20
    System.out.println(sliced.get()); // 30
    System.out.println(sliced.get()); // 40
    System.out.println(sliced.hasRemaining()); // false
}

abstract MappedByteBuffer slice (int index, int length)

Crea un nuevo búfer de bytes cuyo contenido es una subsecuencia compartida del contenido de este búfer. (Traducción automática)

final var file = Path.of("R:", "java-work", "test.data");
System.out.println(file); // R:\java-work\test.data

final byte[] bytes = {10, 20, 30, 40, 50};
Files.write(file, bytes);

try (final var channel = FileChannel.open(file, StandardOpenOption.READ)) {

    final var buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    final var sliced = buffer.slice(2, 3);

    System.out.println(buffer); // java.nio.DirectByteBufferR[pos=0 lim=5 cap=5]
    System.out.println(sliced); // java.nio.DirectByteBufferR[pos=0 lim=3 cap=3]

    System.out.println(buffer.get()); // 10
    System.out.println(buffer.get()); // 20
    System.out.println(buffer.get()); // 30
    System.out.println(buffer.get()); // 40
    System.out.println(buffer.get()); // 50
    System.out.println(buffer.hasRemaining()); // false

    System.out.println(sliced.get()); // 30
    System.out.println(sliced.get()); // 40
    System.out.println(sliced.get()); // 50
    System.out.println(sliced.hasRemaining()); // false
}

Methods declared in ByteBuffer

alignedSlice, alignmentOffset, allocate, allocateDirect, array, arrayOffset, asCharBuffer, asDoubleBuffer, asFloatBuffer, asIntBuffer, asLongBuffer, asReadOnlyBuffer, asShortBuffer, compareTo, equals, get, get, get, get, get, get, getChar, getChar, getDouble, getDouble, getFloat, getFloat, getInt, getInt, getLong, getLong, getShort, getShort, hasArray, hashCode, isDirect, mismatch, order, order, put, put, put, put, put, put, put, put, putChar, putChar, putDouble, putDouble, putFloat, putFloat, putInt, putInt, putLong, putLong, putShort, putShort, toString, wrap, wrap

Consulte el siguiente enlace.

Methods declared in Buffer

capacity, hasRemaining, isReadOnly, limit, position, remaining

Consulte el siguiente enlace.


Related posts

To top of page