使用两种方式复制1.2G文件差异不大,缓冲区设置影响也不大。
ioCopyFile | newIoCopyFile | ||
缓冲区 | 时间 | 缓冲区 | 时间 |
1024 | 49774 | 1024 | 36653 |
2048 | 42632 | 2048 | 35792 |
4096 | 41671 | 4096 | 32142 |
8192 | 34022 | 8192 | 38983 |
16384 | 36983 | 16384 | 36000 |
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyFileTest {
public static void main(String[] args) throws IOException {
new CopyFileTest().ioCopyFile("X:\\archive.zip", "X:\\archive2.zip");
new CopyFileTest().newIoCopyFile("X:\\archive.zip", "X:\\archive2.zip");
}
public void newIoCopyFile(String sourcePath, String destPath) throws IOException {
FileInputStream fi = new FileInputStream(sourcePath);
FileOutputStream fo = new FileOutputStream(destPath);
FileChannel inChannel = fi.getChannel();
FileChannel outChannel = fo.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(16384);
while (true) {
buffer.clear();
int r = inChannel.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
outChannel.write(buffer);
}
}
public void ioCopyFile(String sourcePath, String destPath) throws IOException {
FileInputStream fi = new FileInputStream(sourcePath);
FileOutputStream fo = new FileOutputStream(destPath);
byte b[] = new byte[16384];
while (fi.read(b) != -1) {
fo.write(b);
}
fi.close();
fo.close();
}
}