Tuesday, May 6, 2008

Fastest way to copy files

This uses nio and delegates the work to the underlying os. So this should be the fastest way...

 public static void copy(File srcFile, File destFilethrows IOException {
        FileChannel srcChannel = null;
        FileChannel destChannel = null;
        try {
            srcChannel = new FileInputStream(srcFile).getChannel();
            destChannel = new FileOutputStream(destFile).getChannel();
            long size = srcChannel.size();
            destChannel.transferFrom(srcChannel, 0, size);
        finally {
            if (srcChannel != null)
            if (destChannel != null)


Anonymous said...

Do you have any timings or comparison data?

oae said...

No, but some time ago i did a test and it was a little faster then doing a readByte[] writeByte[] approach.

oae said...

Ok, i did some tests...
To be honest, i couldnt find a clear anser. Sometimes nio was a bit faster, sometimes bio was. But not so much difference.

Also i remember i did those earlier tests not for copying file to file but file to socket. Maybe there a a difference.

Doing some search i found http://www.javalobby.org/java/forums/t17036.html which is interesting to read!