gpt4 book ai didi

java - 以最快的方式复制大文件

转载 作者:行者123 更新时间:2023-12-04 05:18:42 28 4
gpt4 key购买 nike

我试图找到一种以最快的方式复制大文件的方法...

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();
}
}

}

我测试了它,结果非常令人印象深刻......但是有一个大问题,复制的文件比当前文件大很多!!!

所以,请检查一下,帮我找出问题所在,谢谢:))

最佳答案

这是一个 XY 问题。只需使用 Files.copy()

看看那个,看看这对你来说是否不够快:

$ ls -lh ~/ubuntu-13.04-desktop-amd64.iso 
-rw-rw-r-- 1 fge fge 785M Jul 12 2013 /home/fge/ubuntu-13.04-desktop-amd64.iso
$ cat Foo.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Foo
{
public static void main(final String... args)
throws IOException
{
Files.copy(Paths.get("/home/fge/ubuntu-13.04-desktop-amd64.iso"),
Paths.get("/tmp/t.iso"), StandardCopyOption.REPLACE_EXISTING);
}
}
$ time java Foo

real 0m1.860s
user 0m0.077s
sys 0m0.648s
$ time java Foo

real 0m1.851s
user 0m0.101s
sys 0m0.598s

而且还可以更快。天知道为什么,Oracle 不使用 sendfile(2),即使这是 Java 8 和 Linux 2.2 已经存在了很长一段时间。

关于java - 以最快的方式复制大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22503464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com