Copying Files Using NIO

Prior to the JDK 1.4 introduction of the NIO package a tipical file copy routine would look something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void copyFile(File in, File out) throws Exception {
    FileInputStream fis  = new FileInputStream(in);
    FileOutputStream fos = new FileOutputStream(out);
    try {
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (fis != null) fis.close();
        if (fos != null) fos.close();
    }
  }

With the introduction of the NIO package’s conecpt of channels we can rewrite the fileCopy routine as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void copyFile(File in, File out) 
        throws IOException  {
        FileChannel inChannel = new
            FileInputStream(in).getChannel();
        FileChannel outChannel = new
            FileOutputStream(out).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(),
                    outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }

However on windows platforms, you may have to replace

1
2
3
4
try {
            inChannel.transferTo(0, inChannel.size(),
                    outChannel);
        }

with

1
2
3
4
5
6
7
8
9
try {
           // magic number for Windows, 64Mb - 32Kb)
           int maxCount = (64 * 1024 * 1024) - (32 * 1024);
           long size = inChannel.size();
           long position = 0;
           while (position < size) {
              position += 
                inChannel.transferTo(position, maxCount, outChannel);
        }

when attempting to copy a file in excess of 64Mb.



Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)