使用固定大小的块和基于缓冲区的复制,这是一个更好的策略,可以提高文件复制的效率。下面是使用该策略实现的代码:
import java.io.*;
public class BigFileCopy {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final long DEFAULT_CHUNK_SIZE = 1024L * 1024L;
public static void copy(File source, File destination) throws IOException {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
public static void copyFile(File sourceFile, File destFile, int numThreads) throws IOException {
// 分块复制
long fileSize = sourceFile.length();
long chunkSize = Math.max(fileSize / numThreads, DEFAULT_CHUNK_SIZE);
long bytesWritten = 0;
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
for (int i = 0; i < numThreads; i++) {
byte[] bytes = new byte[(int) chunkSize];
int ret = in.read(bytes);
Thread t = new Copier(bytes, ret, out);
t.start();
bytesWritten += ret;
}
// 等待所有线程完成复制
while (bytesWritten < fileSize) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// do nothing
}
}
in.close();
out.close();
}
public static void merge(File sourceDir, File destFile) throws IOException {
OutputStream out = new FileOutputStream(destFile);
for (File file : sourceDir.listFiles()) {
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private static class Copier extends Thread {
private byte[] bytes;
private int length;
private OutputStream out;
public Copier(byte[] bytes, int length, OutputStream out) {
this.bytes = bytes;
this.length = length;
this.out = out;
}
@Override
public void run() {
try {
out.write(bytes, 0, length);
} catch (IOException e) {
// do nothing
}
}
}
}
使用方法:
File sourceFile = new File("source_file_path");
File destFile = new File("destination_file_path");
File tempDir = new File("temp_dir_path");
int numThreads = 4;
// 分块复制
BigFileCopy.copyFile(sourceFile, destFile, numThreads);
// 合并文件
BigFileCopy.merge(tempDir, destFile);
此代码将源文件分成numThreads个块,每个块的大小为chunkSize = max(fileSize / numThreads, DEFAULT_CHUNK_SIZE),并在每个块中运行一个线程,以异步地复制到目标文件。一旦所有线程完成复制,就将所有块合并回单个文件。
请注意,此代码具有默认缓冲区大小和块大小,您可以根据您的需要更改它们。