使用 Java NIO 可以更快地复制文件。我主要通过互联网找到了两种方法来完成这项工作。
public static void copyFile(File sourceFile, File destinationFile) throws IOException {
if (!destinationFile.exists()) {
destinationFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
在20 个对 Java 开发人员非常有用的 Java 代码片段中,我发现了一个不同的评论和技巧:
public static void fileCopy(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); // original -- apparently has trouble copying large files on Windows
// 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);
}
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
但我没有找到或理解什么是意思
“Windows 的幻数,(64Mb - 32Kb)”
它说inChannel.transferTo(0, inChannel.size(), outChannel)
在 Windows 中有问题,32768 (= (64 * 1024 * 1024) - (32 * 1024)) 字节最适合这种方法。