Posts Tagged ‘channel’

Copying file in Java - NIO version

Thursday, February 14th, 2008

In old days, copying a file in Java wasn’t easy: you had to create a array buffer to read from source and write to destination. Now, with NIO from JDK, it’s a matter of creating the streams and let the API do the dirty job.

FileChannel src = new FileInputStream(srcFile).getChannel();
FileChannel dst = new FileOutputStream(dstFile).getChannel();
try {
  dst.transferFrom(src, 0, src.size());
} finally  {
  src.close();
  dst.close();
}