【发布时间】:2014-04-25 13:21:14
【问题描述】:
我试图找到一种以最快的方式复制大文件的方法...
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class FastFileCopy {
public static void main(String[] args) {
try {
String from = "...";
String to = "...";
FileInputStream fis = new FileInputStream(from);
FileOutputStream fos = new FileOutputStream(to);
ArrayList<Transfer> transfers = new ArrayList<>();
long position = 0, estimate;
int count = 1024 * 64;
boolean lastChunk = false;
while (true) {
if (position + count < fis.getChannel().size()) {
transfers.add(new Transfer(fis, fos, position, position + count));
position += count + 1;
estimate = position + count;
if (estimate >= fis.getChannel().size()) {
lastChunk = true;
}
} else {
lastChunk = true;
}
if (lastChunk) {
transfers.add(new Transfer(fis, fos, position, fis.getChannel().size()));
break;
}
}
for (Transfer transfer : transfers) {
transfer.start();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
然后创建这个类:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class Transfer extends Thread {
private FileChannel inChannel = null;
private FileChannel outChannel = null;
private long position, count;
public Transfer(FileInputStream fis, FileOutputStream fos, long position, long count) {
this.position = position;
this.count = count;
inChannel = fis.getChannel();
outChannel = fos.getChannel();
}
@Override
public void run() {
try {
inChannel.transferTo(position, count, outChannel);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我测试了它,结果非常令人印象深刻...... 但是有个大问题,复制出来的文件比现在的文件大很多!!!
所以,请检查并帮助我找到问题,谢谢:))
【问题讨论】:
-
Files.copy(source, destination)对您来说不够快吗?此外,如果文件位于单个硬盘驱动器上,则使用多个线程将降低性能。 -
no :)) ...您可以通过这种方式在 20 秒内复制 3 GB
-
您是否至少尝试过
Files.copy()? -
除了代码中的错误,究竟是什么让您认为多线程会使其更快?你有多线程磁盘吗?也许是条纹?
-
线程不可能加速一个可能占用 1% CPU 的操作。
标签: java multithreading file-copying filechannel