gpt4 book ai didi

java - 下载文件异常处理

转载 作者:行者123 更新时间:2023-11-29 06:21:54 26 4
gpt4 key购买 nike

在我的应用程序中,我从服务器下载了几个关键文件,我想编写一些代码来处理文件下载由于某种原因或其他原因未完成的情况,以便在下次启动时重试下载。然而,一次下载文件的函数仅抛出 MalformedURLException 和 IOException ,但如果抛出这些异常,则意味着下载甚至没有开始。我应该如何安排才能处理下载失败的情况,即使下载已经开始?

void download(String file) throws MalformedURLException ,IOException 
{

BufferedInputStream getit = new BufferedInputStream(new URL(file).openStream());
FileOutputStream saveit = new FileOutputStream(DOWNLOAD_PATH+fileName+"."+ZIP_EXTENSION);
BufferedOutputStream bout = new BufferedOutputStream(saveit,1024);
byte data[] = new byte[1024];
int readed = getit.read(data,0,1024);
while(readed != -1)
{
bout.write(data,0,readed);
readed = getit.read(data,0,1024);
}
bout.close();
getit.close();
saveit.close();

}

最佳答案

您最好使用 Jakarta Commons HttpClient API。

但是,对于您的自定义函数,请查看 https://docs.oracle.com/javase/1.5.0/docs/api/java/io/InterruptedIOException.html 上的 InterruptedIOExceptionbytesTransferred

public class InterruptedIOException
extends IOException

Signals that an I/O operation has been interrupted.

The field bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred.

关于java - 下载文件异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2697490/

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