import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class TransferChannel {
    public static void main(String[] args) throws IOException {
        Path sumber = Path.of("kutipan.txt");
        Path tujuan = Path.of("salinan-transfer.txt");

        try (FileChannel masuk = FileChannel.open(sumber, StandardOpenOption.READ);
             FileChannel keluar = FileChannel.open(tujuan,
                     StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                     StandardOpenOption.TRUNCATE_EXISTING)) {
            long ukuran = masuk.size();
            long dipindah = masuk.transferTo(0, ukuran, keluar);
            System.out.println("ukuran sumber : " + ukuran);
            System.out.println("dipindah      : " + dipindah);
            System.out.println("posisi sumber : " + masuk.position());
        }

        // Files.newByteChannel menghasilkan SeekableByteChannel.
        try (SeekableByteChannel saluran = Files.newByteChannel(sumber)) {
            ByteBuffer penampung = ByteBuffer.allocate(4);
            saluran.read(penampung);
            penampung.flip();
            byte[] sebagian = new byte[penampung.remaining()];
            penampung.get(sebagian);
            System.out.println("4 byte awal   : "
                    + new String(sebagian, StandardCharsets.UTF_8));
            System.out.println("posisi kanal  : " + saluran.position());
        }
    }
}
