Java File copy via FileChannel and ByteBuffer

Description

Java File copy via FileChannel and ByteBuffer

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

public class Main {
  static public void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("infile.txt");
    FileOutputStream fout = new FileOutputStream("outfile.txt");

    FileChannel inc = fin.getChannel();
    FileChannel outc = fout.getChannel();

    ByteBuffer bb = ByteBuffer.allocate(1024);

    while (true) {
      int ret = inc.read(bb);
      if (ret == -1)
        break;// w  w w . j  a v a2s  .c o m
      bb.flip();
      outc.write(bb);
      bb.clear();
    }
  }
}



PreviousNext

Related