Java : FileChannel 示例

Java 中的 FileChannel (Java SE 22 & JDK 22) 及其示例。
您将找到大多数 FileChannel 方法的代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

用于读取、写入、映射和操作文件的通道。 (机器翻译)

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 ()

初始化此类的新实例。 (机器翻译)

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)

强制将对此通道文件的任何更新写入包含该文件的存储设备。 (机器翻译)

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 ()

获取此频道文件的独占锁。 (机器翻译)

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)

获取此频道文件给定区域的锁。 (机器翻译)

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)

将此通道文件的区域直接映射到内存中。 (机器翻译)

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)

将此通道文件的某个区域映射到新映射的内存段中,并具有给定的偏移量、大小和区域。 (机器翻译)

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)

打开或创建一个文件,返回一个文件通道来访问该文件。 (机器翻译)

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)

打开或创建一个文件,返回一个文件通道来访问该文件。 (机器翻译)

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 ()

返回此频道的文件位置。 (机器翻译)

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)

设置此频道的文件位置。 (机器翻译)

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)

从此通道读入一系列字节到给定的缓冲区。 (机器翻译)

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)

从该通道读入字节序列到给定的缓冲区。 (机器翻译)

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)

将字节序列从此通道读入给定缓冲区的子序列中。 (机器翻译)

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)

从给定的文件位置开始,从该通道将一系列字节读入给定的缓冲区。 (机器翻译)

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 ()

返回此频道文件的当前大小。 (机器翻译)

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)

从给定的可读字节通道将字节传输到此通道的文件中。 (机器翻译)

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)

将字节从此通道的文件传输到给定的可写字节通道。 (机器翻译)

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)

将此频道的文件截断为给定的大小。 (机器翻译)

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 ()

尝试获取此频道文件的独占锁。 (机器翻译)

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)

尝试获取此频道文件给定区域的锁。 (机器翻译)

Please see :

abstract int write (ByteBuffer src)

从给定的缓冲区将字节序列写入此通道。 (机器翻译)

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)

从给定的缓冲区将字节序列写入此通道。 (机器翻译)

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)

从给定缓冲区的子序列中将字节序列写入此通道。 (机器翻译)

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)

从给定的缓冲区,从给定的文件位置开始,将一系列字节写入此通道。 (机器翻译)

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

请参阅下面的链接。

Methods declared in Channel

isOpen

请参阅下面的链接。


相关文章

To top of page