Extreme Java When vanilla Java is not enough

14Feb/080

Copying file in Java – NIO version

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();
}