Copying Files Using NIO
25 Oct 2008Prior to the JDK 1.4 introduction of the NIO package a tipical file copy routine would look something like:
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:
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
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
with
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.