Android 使用Get方式实现断点下载(一)
发布日期:2021-06-30 22:35:08 浏览次数:3 分类:技术文章

本文共 3854 字,大约阅读时间需要 12 分钟。

public class DownloadActivity extends Activity implements OnClickListener{
private String path; private static final int THREAD_NUM = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = new Button(this); button.setOnClickListener(this); } @Override public void onClick(View v) { download(path); } private void download(String path) { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200) { int length = conn.getContentLength(); RandomAccessFile raf = new RandomAccessFile("down.exe", "rwd"); raf.setLength(length); raf.close(); int blocksize = length / THREAD_NUM; for (int i = 1; i <= THREAD_NUM; i++) { int start = (i-1) * blocksize; int end = i * blocksize - 1; if (i == THREAD_NUM) { end = length; } System.out.println("线程:"+i + "下载:" + start + "---->" + end); new DownloadThread(i, start, end, path).start(); } }else { System.out.println("服务器错误!"); } } catch (Exception e) { e.printStackTrace(); } } class DownloadThread extends Thread{ private int threadId; private int start; private int end; private String path; public DownloadThread(int threadId,int start,int end, String path){ this.threadId = threadId; this.start = start; this.end = end; this.path = path; } @Override public void run() { try { int tempLen=0; //先读取临时文件 File temFile = new File(threadId+".txt"); if (temFile.exists()) { FileInputStream fis = new FileInputStream(temFile); byte[] buffer = new byte[1024]; int len = fis.read(buffer); tempLen = Integer.parseInt(new String(buffer,0,len)); start += tempLen; } URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes=" + start + "-" + end); conn.setConnectTimeout(5000); int total=0; if (conn.getResponseCode() == 206) { InputStream inputStream = conn.getInputStream(); RandomAccessFile raf = new RandomAccessFile("down.exe", "rwd"); raf.seek(start); byte[] buffer = new byte[1024]; int len = -1; while((len = inputStream.read(buffer))!=-1){ RandomAccessFile tempRaf = new RandomAccessFile(threadId+".txt", "rwd"); raf.write(buffer, 0 , len); total+=len; System.out.println("线程:"+threadId + "下载total:" + total); tempRaf.write(((tempLen + total) + "").getBytes()); tempRaf.close(); } raf.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }}

转载地址:https://lovoo.blog.csdn.net/article/details/51232042 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Anroid 加载图片方式一 使用SmartImageView
下一篇:Android 简单模仿AsyncHttpClient

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月18日 16时46分59秒