gpt4 book ai didi

java - java中的多线程下载器

转载 作者:行者123 更新时间:2023-11-30 08:18:31 25 4
gpt4 key购买 nike

好的,我正在使用以下函数创建多个线程来下载文件。您可以看到该函数将链接、起始字节、结束字节和下载文件的路径作为参数。我调用该函数两次以创建两个线程来下载所需的文件。

例如,如果文件有 100 字节,我会执行以下操作

thread-1 --> DownloadFile("http://localhost/file.zip ", 0, 50, "output.zip");

thread-2 --> DownloadFile("http://localhost/file.zip ", 50, 100, "output.zip");

但是你知道会发生什么,只有几个字节没有下载,我的进度条停留在 99%。这就是问题所在!!!

为什么卡在99%?换句话说,为什么有些字节会丢失?我可以看到下载的变量中的总字节数。

这是函数

public void DownloadFile(final String link, final long start,final long end, final String path){
new Thread(new Runnable(){
public void run(){
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
RandomAccessFile raf = new RandomAccessFile(path,"rw");
raf.seek(start);

int i=0;
byte bytes[] = new byte[1024];


while((i = bis.read(bytes))!=-1){
raf.write(bytes, 0, i);
downloaded = downloaded+i;
int perc = (int) ((downloaded*100)/FileSize);
progress.setValue(perc);
percentLabel.setText(Long.toString(downloaded)+" out of "+FileSize);
}


if(FileSize==downloaded){
progress.setValue(100);
JOptionPane.showMessageDialog(null, "Download Success! ");
progress.setValue(0);
downloaded=0;
downBtn.setText("Download");
}
bis.close();
raf.close();


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}).start();
}

感谢期待。

最佳答案

RandomAccessFile is not thread safe.

raf.seek(begin) 失败,请参阅 RandomAccessFile.seek() 的文档

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file.

您可以将文件的各个部分下载到单独的文件中,然后合并它们。

您确定并行下载速度更快吗?

关于java - java中的多线程下载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29317339/

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