/**
* 单线程支持断点续传下载
* 断点续传
*/
public static void downloadFile(final DownLoadProgressListener loadProgressListener) {
Runnable runnable = new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
try {
URL url = new URL("https://codeload.github.com/yanzhenjie/Sofia/zip/master");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
// 设置User-Agent
httpConnection.setRequestProperty("User-Agent", "NetFox");
// setHeader(httpConnection);
long bytes = AppConfig.getInstance().getLong("length", 0L);
// 得到content的长度
// 设置断点续传的开始位置
httpConnection.setRequestProperty("Range", "bytes=" + bytes + "-");
long contentLength = httpConnection.getContentLengthLong();
Log.i(TAG, "---" + "bytes=" + bytes + "-" + contentLength);
// 获得输入流
InputStream input = httpConnection.getInputStream();
File file = FileUtils.getLocalFile("Sofia.zip");
// 采用IO包中的RandAccessFile类。
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
long position = bytes;
//定位文件指针到nPos位置
accessFile.seek(position);
byte[] buffer = new byte[1024];
long total = position;
int statPosition = Integer.valueOf(position + "");
int len = -1;
long sTime = System.currentTimeMillis();
long eTime = 0;
int p = 0;
//跳过已经读取过的
long skipL = input.skip(position);
Log.i(TAG, " nStartPos --> " + position + ", skipL = " +
skipL);
// skipBytesFromStream(input, position);
//从输入流中读入字节流,然后写到文件中
while ((len = input.read(buffer, 0, 1024)) > 0) {
accessFile.write(buffer, 0, len);
total = total + len;
//记录文件日志长度
AppConfig.getInstance().putLong("length", total);
eTime = System.currentTimeMillis();
if (eTime - sTime > 200) {
//大于500ms 才进行一次监听
sTime = eTime;
Log.i(TAG, "file---Length:" + total);
loadProgressListener.onProgressUpdate(total, contentLength);
}
}
loadProgressListener.onCompleteLoad(contentLength);
Log.i(TAG, "file---end:" + total);
} catch (IOException e) {
e.printStackTrace();
loadProgressListener.onError(0);
}
}
};
AppContext.MAIN_EXECUTOR.execute(runnable);
}
public interface DownLoadProgressListener {
void onProgressUpdate(long percent, long length);
void onCompleteLoad(long length);
void onError(int error);
}
文件断点续传
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 本文续接我上一篇文章《Android实战:简易断点续传下载器实现》链接地址:http://www.jianshu....
- 最近在搞视频爬虫,之前都是使用获取到视频连接后太多调用迅雷批量下载的方式进行下载,但是迅雷批量下载有限制,而且需要...
- @interface FileDownloader() <NSURLConnectionDataDelegate>...