Java text file copy using FileChannel and ByteBuffer

Description

Java text file copy using FileChannel and ByteBuffer

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

public class Main {
  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.allocateDirect(32 * 1024);

    while (in.read(buff) > 0) {
      buff.flip();/*from  w w  w.  jav  a 2s  .  c  o m*/
      out.write(buff);
      buff.clear();
    }

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



PreviousNext

Related