gpt4 book ai didi

java - 在文件下载中实现暂停/恢复

转载 作者:IT老高 更新时间:2023-10-28 20:52:46 28 4
gpt4 key购买 nike

我正在尝试在我的下载管理器中实现暂停/恢复,我在网上搜索并阅读了几篇文章并根据它们更改了我的代码,但恢复似乎无法正常工作,有什么想法吗?

                if (!downloadPath.exists()) 
downloadPath.mkdirs();

if (outputFileCache.exists())
{
downloadedSize = outputFileCache.length();
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + downloadedSize + "-");
connection.setConnectTimeout(14000);
connection.connect();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(outputFileCache, true);
input.skip(downloadedSize); //Skip downloaded size
}
else
{
connection.setConnectTimeout(14000);
connection.connect();
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(outputFileCache);
}

fileLength = connection.getContentLength();


byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
long total = downloadedSize;

while ((count = input.read(data)) != -1 && !this.isInterrupted())
{
total += count;
output.write(data, 0, count);
__progress = (int) (total * 100 / fileLength);

}
output.flush();
output.close();
input.close();

最佳答案

好的问题已解决,这是我为其他想要实现暂停/恢复的用户提供的代码:

        if (outputFileCache.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}

connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();

if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");

if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
downloadedSize = Long.valueOf(connectionRanges[0]);
}

if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();

fileLength = connection.getContentLength() + downloadedSize;
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(downloadedSize);

byte data[] = new byte[1024];
int count = 0;
int __progress = 0;

while ((count = input.read(data, 0, 1024)) != -1
&& __progress != 100)
{
downloadedSize += count;
output.write(data, 0, count);
__progress = (int) ((downloadedSize * 100) / fileLength);
}

output.close();
input.close();
}

关于java - 在文件下载中实现暂停/恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349296/

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