Java : FileChannel con ejemplos

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

Nota :


Summary

Un canal para leer, escribir, mapear y manipular un archivo. (Traducción automática)

Class diagram

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

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

    final var src = ByteBuffer.allocate(5)
            .put((byte) 10)
            .put((byte) 20)
            .put((byte) 30)
            .put((byte) 40)
            .put((byte) 50)
            .clear();

    final var ret = channel.write(src);
    System.out.println(ret); // 5
}

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

    final var dst = ByteBuffer.allocate(5);
    final var ret = channel.read(dst);
    System.out.println(ret); // 5

    if (dst.hasArray()) {
        // [10, 20, 30, 40, 50]
        System.out.println(Arrays.toString(dst.array()));
    }
}

Constructors

FileChannel ()

Inicializa una nueva instancia de esta clase. (Traducción automática)

protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.

Methods

abstract void force (boolean metaData)

Fuerza a que cualquier actualización del archivo de este canal se escriba en el dispositivo de almacenamiento que lo contiene. (Traducción automática)

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

System.out.println(Files.notExists(path)); // true

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

    final byte[] array = {10, 20, 30, 40, 50};
    final var src = ByteBuffer.wrap(array);

    // --- PowerShell ---
    //PS R:\java-work> ls | Format-Table -Property Length, Name
    //
    //Length Name
    //------ ----
    //     0 test.data

    System.out.println(channel.write(src)); // 5
    System.out.println(channel.size()); // 5

    // --- PowerShell ---
    //PS R:\java-work> ls | Format-Table -Property Length, Name
    //
    //Length Name
    //------ ----
    //     0 test.data

    channel.force(true);

    // --- PowerShell ---
    //PS R:\java-work> ls | Format-Table -Property Length, Name
    //
    //Length Name
    //------ ----
    //     5 test.data
}

final FileLock lock ()

Adquiere un bloqueo exclusivo en el archivo de este canal. (Traducción automática)

Please see also : FileLock

public class Child {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 1) {
            throw new IllegalArgumentException();
        }

        final var name = "child " + args[0];

        final var file = Path.of("lock.txt");
        try (final var channel = FileChannel.open(
                file, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

            System.out.printf("  %s : lock start ...%n", name);
            try (final var lock = channel.lock()) {

                TimeUnit.MILLISECONDS.sleep(100);

                System.out.printf("  %s :   *** lock OK! ***%n", name);
                System.out.printf("  %s :   sleep 5 seconds ...%n", name);

                TimeUnit.SECONDS.sleep(5);
                System.out.printf("  %s :   sleep end%n", name);
            }

            System.out.printf("  %s : lock end%n", name);
        }
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main : start");

        final var p1 = new ProcessBuilder("java", "Child", "1").inheritIO().start();
        TimeUnit.MILLISECONDS.sleep(10);
        final var p2 = new ProcessBuilder("java", "Child", "2").inheritIO().start();

        p1.waitFor();
        p2.waitFor();

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//  child 1 : lock start ...
//  child 2 : lock start ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 2 :   sleep end
//  child 2 : lock end
//main : end

abstract FileLock lock (long position, long size, boolean shared)

Adquiere un bloqueo en la región dada del archivo de este canal. (Traducción automática)

An example for position and size parameters.

public class Child {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 3) {
            throw new IllegalArgumentException();
        }

        final var name = "child " + args[0];
        final var position = Long.parseLong(args[1]);
        final var size = Long.parseLong(args[2]);

        final var file = Path.of("lock.txt");
        try (final var channel = FileChannel.open(
                file, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

            System.out.printf("  %s : lock start (position=%d, size=%d) ...%n",
                    name, position, size);
            try (final var lock = channel.lock(position, size, false)) {

                TimeUnit.MILLISECONDS.sleep(100);

                System.out.printf("  %s :   *** lock OK! ***%n", name);
                System.out.printf("  %s :   sleep 5 seconds ...%n", name);

                TimeUnit.SECONDS.sleep(5);
                System.out.printf("  %s :   sleep end%n", name);
            }

            System.out.printf("  %s : lock end%n", name);
        }
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 2) {
            throw new IllegalArgumentException();
        }

        System.out.println("main : start");

        final var p1 = new ProcessBuilder("java", "Child", "1", "0", "10").inheritIO().start();
        TimeUnit.MILLISECONDS.sleep(10);
        final var p2 = new ProcessBuilder("java", "Child", "2", args[0], args[1]).inheritIO().start();

        p1.waitFor();
        p2.waitFor();

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main 0 10
//main : start
//  child 1 : lock start (position=0, size=10) ...
//  child 2 : lock start (position=0, size=10) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 2 :   sleep end
//  child 2 : lock end
//main : end
//
//> java Main 11 5
//main : start
//  child 1 : lock start (position=0, size=10) ...
//  child 2 : lock start (position=11, size=5) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   sleep end
//  child 2 : lock end
//main : end

An example for the shared parameter.

public class Child {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 2) {
            throw new IllegalArgumentException();
        }

        final var name = "child " + args[0];
        final var shared = "shared".equals(args[1]);

        final var file = Path.of("lock.txt");
        try (final var channel = FileChannel.open(file, StandardOpenOption.CREATE,
                StandardOpenOption.WRITE, StandardOpenOption.READ)) {

            System.out.printf("  %s : lock start (shared=%b) ...%n", name, shared);
            try (final var lock = channel.lock(0, Long.MAX_VALUE, shared)) {

                TimeUnit.MILLISECONDS.sleep(100);

                System.out.printf("  %s :   *** lock OK! ***%n", name);
                System.out.printf("  %s :   sleep 5 seconds ...%n", name);

                TimeUnit.SECONDS.sleep(5);
                System.out.printf("  %s :   sleep end%n", name);
            }

            System.out.printf("  %s : lock end%n", name);
        }
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 2) {
            throw new IllegalArgumentException();
        }

        System.out.println("main : start");

        final var p1 = new ProcessBuilder("java", "Child", "1", args[0]).inheritIO().start();
        TimeUnit.MILLISECONDS.sleep(10);
        final var p2 = new ProcessBuilder("java", "Child", "2", args[1]).inheritIO().start();

        p1.waitFor();
        p2.waitFor();

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main shared shared
//main : start
//  child 1 : lock start (shared=true) ...
//  child 2 : lock start (shared=true) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   sleep end
//  child 2 : lock end
//main : end
//
//> java Main shared exclusive
//main : start
//  child 1 : lock start (shared=true) ...
//  child 2 : lock start (shared=false) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 2 :   sleep end
//  child 2 : lock end
//main : end
//
//> java Main exclusive shared
//main : start
//  child 1 : lock start (shared=false) ...
//  child 2 : lock start (shared=true) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 2 :   sleep end
//  child 2 : lock end
//main : end
//
//> java Main exclusive exclusive
//main : start
//  child 1 : lock start (shared=false) ...
//  child 2 : lock start (shared=false) ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 5 seconds ...
//  child 1 :   sleep end
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 5 seconds ...
//  child 2 :   sleep end
//  child 2 : lock end
//main : end

abstract MappedByteBuffer map (FileChannel.MapMode mode, long position, long size)

Asigna una región del archivo de este canal directamente a la memoria. (Traducción automática)

Please see also : MappedByteBuffer

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

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

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

    final var buffer = channel.map(
            FileChannel.MapMode.READ_WRITE, 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(path);
        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(path);
        System.out.println(Arrays.toString(ret)); // [-10, -20, -30, 40, 50]
    }
}

MemorySegment map (FileChannel.MapMode mode, long offset, long size, Arena arena)

Asigna una región del archivo de este canal a un nuevo segmento de memoria asignado, con el desplazamiento, tamaño y arena dados. (Traducción automática)

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

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

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

    final var segment = channel.map(
            FileChannel.MapMode.READ_WRITE, 0, channel.size(), Arena.ofAuto());

    {

        final var dst = segment.toArray(ValueLayout.JAVA_BYTE);
        System.out.println(Arrays.toString(dst)); // [10, 20, 30, 40, 50]

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

    segment.set(ValueLayout.JAVA_BYTE, 0, (byte) -10);
    segment.set(ValueLayout.JAVA_BYTE, 1, (byte) -20);
    segment.set(ValueLayout.JAVA_BYTE, 2, (byte) -30);

    {
        final var dst = segment.toArray(ValueLayout.JAVA_BYTE);
        System.out.println(Arrays.toString(dst)); // [-10, -20, -30, 40, 50]

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

static FileChannel open (Path path, OpenOption... options)

Abre o crea un archivo, devolviendo un canal de archivo para acceder al archivo. (Traducción automática)

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

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

    final var src = ByteBuffer.allocate(5)
            .put((byte) 10)
            .put((byte) 20)
            .put((byte) 30)
            .put((byte) 40)
            .put((byte) 50)
            .clear();

    final var ret = channel.write(src);
    System.out.println(ret); // 5
}

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

    final var dst = ByteBuffer.allocate(5);
    final var ret = channel.read(dst);
    System.out.println(ret); // 5

    if (dst.hasArray()) {
        // [10, 20, 30, 40, 50]
        System.out.println(Arrays.toString(dst.array()));
    }
}

static FileChannel open (Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)

Abre o crea un archivo, devolviendo un canal de archivo para acceder al archivo. (Traducción automática)

Please see also open(Path path, OpenOption... options) for parameters other than the attrs parameter.

The following code runs on Linux.

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("os.name")); // Linux

        {
            final var file = Path.of("sample1.txt");
            try (final var _ = FileChannel.open(file,
                    Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE))) {
            }

            // --- Linux Terminal ---
            //$ ls -l sample1.txt
            //-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt
        }

        {
            final var permissions = PosixFilePermissions.fromString("rw-r-----");
            final var attrs = PosixFilePermissions.asFileAttribute(permissions);

            final var file = Path.of("sample2.txt");
            try (final var _ = FileChannel.open(file,
                    Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE),
                    attrs)) {
            }

            // --- Linux Terminal ---
            //$ ls -l sample2.txt
            //-rw-r----- 1 xxxx xxxx 0 ... sample2.txt
        }
    }
}

abstract long position ()

Devuelve la posición del archivo de este canal. (Traducción automática)

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

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

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

    final var ret1 = channel.position(2);
    System.out.println(channel.equals(ret1)); // true

    {
        System.out.println(channel.position()); // 2

        final var buffer = ByteBuffer.allocate(3);
        final var ret = channel.read(buffer);
        System.out.println(ret); // 3

        System.out.println(channel.position()); // 5

        if (buffer.hasArray()) {
            // [30, 40, 50]
            System.out.println(Arrays.toString(buffer.array()));
        }
    }

    final var ret2 = channel.position(0);
    System.out.println(channel.equals(ret2)); // true

    {
        System.out.println(channel.position()); // 0

        final var buffer = ByteBuffer.allocate(5);
        final var ret = channel.read(buffer);
        System.out.println(ret); // 5

        System.out.println(channel.position()); // 5

        if (buffer.hasArray()) {
            // [10, 20, 30, 40, 50]
            System.out.println(Arrays.toString(buffer.array()));
        }
    }
}

abstract FileChannel position (long newPosition)

Establece la posición del archivo de este canal. (Traducción automática)

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

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

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

    final var ret1 = channel.position(2);
    System.out.println(channel.equals(ret1)); // true

    {
        System.out.println(channel.position()); // 2

        final var buffer = ByteBuffer.allocate(3);
        final var ret = channel.read(buffer);
        System.out.println(ret); // 3

        System.out.println(channel.position()); // 5

        if (buffer.hasArray()) {
            // [30, 40, 50]
            System.out.println(Arrays.toString(buffer.array()));
        }
    }

    final var ret2 = channel.position(0);
    System.out.println(channel.equals(ret2)); // true

    {
        System.out.println(channel.position()); // 0

        final var buffer = ByteBuffer.allocate(5);
        final var ret = channel.read(buffer);
        System.out.println(ret); // 5

        System.out.println(channel.position()); // 5

        if (buffer.hasArray()) {
            // [10, 20, 30, 40, 50]
            System.out.println(Arrays.toString(buffer.array()));
        }
    }
}

abstract int read (ByteBuffer dst)

Lee una secuencia de bytes de este canal en el búfer indicado. (Traducción automática)

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

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

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

    final var array = new byte[5];
    final var dst = ByteBuffer.wrap(array);

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
    System.out.println(Arrays.toString(array)); // [0, 0, 0, 0, 0]

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

    final var ret = channel.read(dst);
    System.out.println(ret); // 3

    System.out.println(channel.position()); // 3

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=3 lim=5 cap=5]
    System.out.println(Arrays.toString(array)); // [10, 20, 30, 0, 0]
}

final long read (ByteBuffer[] dsts)

Lee una secuencia de bytes de este canal en los buffers dados. (Traducción automática)

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

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

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

    final ByteBuffer[] dsts = {
            ByteBuffer.allocate(2),
            ByteBuffer.allocate(3),
            ByteBuffer.allocate(4),
    };

    final var ret = channel.read(dsts);
    System.out.println(ret); // 9

    System.out.println("-- dsts --");
    for (final var dst : dsts) {
        if (dst.hasArray()) {
            System.out.println(Arrays.toString(dst.array()));
        }
    }

    // Result
    // ↓
    //-- dsts --
    //[10, 20]
    //[30, 40, 50]
    //[60, 70, 80, 90]
}

abstract long read (ByteBuffer[] dsts, int offset, int length)

Lee una secuencia de bytes de este canal en una subsecuencia de los buffers dados. (Traducción automática)

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

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

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

    final ByteBuffer[] dsts = {
            ByteBuffer.allocate(1),
            ByteBuffer.allocate(2),
            ByteBuffer.allocate(3),
            ByteBuffer.allocate(4),
            ByteBuffer.allocate(5),
    };

    final var ret = channel.read(dsts, 1, 3);
    System.out.println(ret); // 9

    System.out.println("-- dsts --");
    for (final var dst : dsts) {
        if (dst.hasArray()) {
            System.out.println(Arrays.toString(dst.array()));
        }
    }

    // Result
    // ↓
    //-- dsts --
    //[0]
    //[10, 20]
    //[30, 40, 50]
    //[60, 70, 80, 90]
    //[0, 0, 0, 0, 0]
}

abstract int read (ByteBuffer dst, long position)

Lee una secuencia de bytes de este canal en el búfer dado, comenzando en la posición de archivo dada. (Traducción automática)

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

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

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

    final var array = new byte[5];
    final var dst = ByteBuffer.wrap(array);

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
    System.out.println(Arrays.toString(array)); // [0, 0, 0, 0, 0]

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

    final var ret = channel.read(dst, 2);
    System.out.println(ret); // 3

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

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=3 lim=5 cap=5]
    System.out.println(Arrays.toString(array)); // [30, 40, 50, 0, 0]
}

abstract long size ()

Devuelve el tamaño actual del archivo de este canal. (Traducción automática)

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

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

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

    final var size = channel.size();
    System.out.println(size); // 5

    final var dst = ByteBuffer.allocate(Math.toIntExact(size));
    System.out.println(channel.read(dst)); // 5

    if (dst.hasArray()) {
        // [10, 20, 30, 40, 50]
        System.out.println(Arrays.toString(dst.array()));
    }
}

abstract long transferFrom (ReadableByteChannel src, long position, long count)

Transfiere bytes al archivo de este canal desde el canal de bytes legible indicado. (Traducción automática)

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

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

Files.write(srcPath, new byte[]{10, 20, 30});

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

    System.out.println(channel.size()); // 0

    try (final var src = FileChannel.open(srcPath, StandardOpenOption.READ)) {

        final var ret = channel.transferFrom(src, 0, src.size());
        System.out.println(ret); // 3
    }
}

final var bytes = Files.readAllBytes(dstPath);
System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
final var srcPath = Path.of("R:", "java-work", "src.data");
System.out.println(srcPath); // R:\java-work\src.data

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

Files.write(srcPath, new byte[]{10, 20, 30});
Files.write(dstPath, new byte[]{-1, -2, -3, -4, -5, -6, -7});

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

    System.out.println(channel.size()); // 7

    try (final var src = FileChannel.open(srcPath, StandardOpenOption.READ)) {

        final var ret = channel.transferFrom(src, 2, 3);
        System.out.println(ret); // 3
    }
}

final var bytes = Files.readAllBytes(dstPath);
System.out.println(Arrays.toString(bytes)); // [-1, -2, 10, 20, 30, -6, -7]

abstract long transferTo (long position, long count, WritableByteChannel target)

Transfiere bytes del archivo de este canal al canal de bytes escribible indicado. (Traducción automática)

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

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

Files.write(srcPath, new byte[]{10, 20, 30});

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

    System.out.println(channel.size()); // 3

    try (final var target = FileChannel.open(dstPath,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

        final var ret = channel.transferTo(0, channel.size(), target);
        System.out.println(ret); // 3
    }
}

final var bytes = Files.readAllBytes(dstPath);
System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
final var srcFile = Path.of("R:", "java-work", "src.data");
System.out.println(srcFile); // R:\java-work\src.data

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

Files.write(srcFile, new byte[]{10, 20, 30, 40, 50, 60, 70});

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

    System.out.println(channel.size()); // 7

    try (final var target = FileChannel.open(dstFile,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

        final var ret = channel.transferTo(2, 3, target);
        System.out.println(ret); // 3
    }
}

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

abstract FileChannel truncate (long size)

Trunca el archivo de este canal al tamaño indicado. (Traducción automática)

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

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

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

    final var ret = channel.truncate(3);
    System.out.println(channel.equals(ret)); // true

    final var size = channel.size();
    System.out.println(size); // 3
}

// [10, 20, 30]
System.out.println(Arrays.toString(Files.readAllBytes(path)));

final FileLock tryLock ()

Intenta adquirir un bloqueo exclusivo en el archivo de este canal. (Traducción automática)

Please see also : FileLock

public class Child {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length != 1) {
            throw new IllegalArgumentException();
        }

        final var name = "child " + args[0];

        final var file = Path.of("lock.txt");
        try (final var channel = FileChannel.open(
                file, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

            System.out.printf("  %s : lock start ...%n", name);

            while (true) {
                try (final var lock = channel.tryLock()) {

                    TimeUnit.MILLISECONDS.sleep(100);

                    if (lock != null) {
                        System.out.printf("  %s :   *** lock OK! ***%n", name);
                        System.out.printf("  %s :   sleep 3 seconds ...%n", name);
                        TimeUnit.SECONDS.sleep(3);
                        break;
                    } else {
                        System.out.printf("  %s :   ### lock NG! ###%n", name);
                        System.out.printf("  %s :   sleep 1 second ...%n", name);
                        TimeUnit.SECONDS.sleep(1);
                    }
                }
            }

            System.out.printf("  %s : lock end%n", name);
        }
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main : start");

        final var p1 = new ProcessBuilder("java", "Child", "1").inheritIO().start();
        TimeUnit.MILLISECONDS.sleep(10);
        final var p2 = new ProcessBuilder("java", "Child", "2").inheritIO().start();

        p1.waitFor();
        p2.waitFor();

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//  child 1 : lock start ...
//  child 2 : lock start ...
//  child 1 :   *** lock OK! ***
//  child 1 :   sleep 3 seconds ...
//  child 2 :   ### lock NG! ###
//  child 2 :   sleep 1 second ...
//  child 2 :   ### lock NG! ###
//  child 2 :   sleep 1 second ...
//  child 2 :   ### lock NG! ###
//  child 2 :   sleep 1 second ...
//  child 1 : lock end
//  child 2 :   *** lock OK! ***
//  child 2 :   sleep 3 seconds ...
//  child 2 : lock end
//main : end

abstract FileLock tryLock (long position, long size, boolean shared)

Intenta adquirir un bloqueo en la región dada del archivo de este canal. (Traducción automática)

Please see :

abstract int write (ByteBuffer src)

Escribe una secuencia de bytes en este canal desde el búfer indicado. (Traducción automática)

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

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

    final byte[] array = {10, 20, 30, 40, 50};
    final var src = ByteBuffer.wrap(array);

    System.out.println(src); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
    System.out.println(channel.position()); // 0

    final var ret = channel.write(src);
    System.out.println(ret); // 5

    System.out.println(src); // java.nio.HeapByteBuffer[pos=5 lim=5 cap=5]
    System.out.println(channel.position()); // 5
}

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

final long write (ByteBuffer[] srcs)

Escribe una secuencia de bytes en este canal desde los buffers indicados. (Traducción automática)

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

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

    final ByteBuffer[] srcs = {
            ByteBuffer.wrap(new byte[]{10, 20}),
            ByteBuffer.wrap(new byte[]{30, 40, 50}),
            ByteBuffer.wrap(new byte[]{60, 70, 80, 90}),
    };

    final var ret = channel.write(srcs);
    System.out.println(ret); // 9
}

final var bytes = Files.readAllBytes(path);

// [10, 20, 30, 40, 50, 60, 70, 80, 90]
System.out.println(Arrays.toString(bytes));

abstract long write (ByteBuffer[] srcs, int offset, int length)

Escribe una secuencia de bytes en este canal desde una subsecuencia de los buffers dados. (Traducción automática)

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

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

    final ByteBuffer[] srcs = {
            ByteBuffer.wrap(new byte[]{10}),
            ByteBuffer.wrap(new byte[]{20, 30}),
            ByteBuffer.wrap(new byte[]{40, 50, 60}),
            ByteBuffer.wrap(new byte[]{70, 80, 90, 100}),
    };

    final var ret = channel.write(srcs, 1, 2);
    System.out.println(ret); // 5
}

final var bytes = Files.readAllBytes(path);

// [20, 30, 40, 50, 60]
System.out.println(Arrays.toString(bytes));

abstract int write (ByteBuffer src, long position)

Escribe una secuencia de bytes en este canal desde el búfer dado, comenzando en la posición de archivo dada. (Traducción automática)

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

Files.write(path, new byte[]{-1, -2, -3, -4, -5, -6, -7});

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

    final byte[] array = {10, 20, 30};
    final var src = ByteBuffer.wrap(array);

    System.out.println(src); // java.nio.HeapByteBuffer[pos=0 lim=3 cap=3]
    System.out.println(channel.position()); // 0

    final var ret = channel.write(src, 2);
    System.out.println(ret); // 3

    System.out.println(src); // java.nio.HeapByteBuffer[pos=3 lim=3 cap=3]
    System.out.println(channel.position()); // 0
}

final var bytes = Files.readAllBytes(path);
System.out.println(Arrays.toString(bytes)); // [-1, -2, 10, 20, 30, -6, -7]

Methods declared in AbstractInterruptibleChannel

begin, close, end, implCloseChannel, isOpen

Consulte el siguiente enlace.

Methods declared in Channel

isOpen

Consulte el siguiente enlace.


Related posts

To top of page