我正在整理一些代码,以便从Android中的HTTP地址下载文件。如果下载失败,我想支持下载恢复。
开始下载时获得的输出,然后杀死wifi连接并重新启动几次,如下:
开始大小0 停止尺寸12333416 起始尺寸12333416 停止尺寸 16058200 起始尺寸 3724784
我无法理解为什么在第一次恢复后,部分下载的文件的后续文件大小读数不匹配。
提前致谢!
public void download(String source, String target) throws IOException {
BufferedOutputStream outputStream = null;
InputStream inputStream = null;
try {
File targetFile = new File(target);
currentBytes = targetFile.length();
Log.i(TAG, "Start size " + String.valueOf(currentBytes));
outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
// create the input stream
URLConnection connection = (new URL(source)).openConnection();
connection.setConnectTimeout(mCoTimeout);
connection.setReadTimeout(mSoTimeout);
inputStream = connection.getInputStream();
inputStream.skip(currentBytes);
// calculate the total bytes
totalBytes = connection.getContentLength();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
// write the bytes to file
outputStream.write(buffer, 0, bytesRead);
outputStream.flush();
currentBytes += bytesRead;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
// close the output stream
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
// close the input stream
inputStream.close();
}
Log.i(TAG, "Stop size " + String.valueOf(currentBytes));
}
}
答案 0 :(得分:1)
你做错了两件事:
要恢复下载到文件,您应该追加,而不是重写文件。对输出流使用特殊构造函数:
FileOutputStream(targetFile,true)
要从服务器请求部分文件,您应该使用HTTP 1.1属性“Range”。你可以这样做:
HttpURLConnection httpConnection =(HttpURLConnection)连接; connection.setRequestProperty(“Range”,“bytes =”+ currentBytes +“ - ”);