CopyChannels.java Source code

Java tutorial

Introduction

Here is the source code for CopyChannels.java

Source

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyChannels {
    public static void main(String[] args) throws Exception {
        String fromFileName = "from.txt";
        String toFileName = "to.txt";
        FileChannel in = new FileInputStream(fromFileName).getChannel();
        FileChannel out = new FileOutputStream(toFileName).getChannel();

        ByteBuffer buff = ByteBuffer.allocate(32 * 1024);

        while (in.read(buff) > 0) {
            buff.flip();
            out.write(buff);
            buff.clear();
        }

        in.close();
        out.close();
    }
}