android下载文件,支持续传

本文介绍了一个使用Java实现的多线程断点续传下载应用案例。该应用可以将大文件分成多个部分同时下载,提高了下载速度。通过记录已下载的部分,实现了断点续传的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.dong.download.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Administrator
 *黑马 BASE 65课
 */
public class MainActivity extends Activity {

	public static final int TEXTVIEW_PROGRESS = 2;
	private Button b;
	private ProgressBar bar;
	private EditText ed;
	// 和现在线程数相同,为了记录关闭线程时的计数器
	static int deleteFileThread = 3;
	private TextView tv;
	static int threadCont = 3;

	int currentProcess = 0;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case 1:
				Toast.makeText(MainActivity.this, "服务器错误", 1).show();
				break;
			case TEXTVIEW_PROGRESS:
				tv.setText(""+(bar.getProgress()*100/bar.getMax()));
				break;
			case 3:

				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		b = (Button) findViewById(R.id.button1);
		bar = (ProgressBar) findViewById(R.id.pb);
		ed = (EditText) findViewById(R.id.et_path);
		tv = (TextView)findViewById(R.id.tv);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void download(View v) {
		//String path = ed.getText().toString().trim();

		new Thread() {
			public void run() {
				try {
					String path = "http://192.168.1.100:8080/cbox2.4.0.9.exe";
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");
					int code = conn.getResponseCode();
					if (200 == code) {
						int length = conn.getContentLength();
						bar.setMax(length);
						System.out.println("file length is" + length);
						// 创建一个文件
						RandomAccessFile raf = new RandomAccessFile(
								"/sdcard/cbox2.4.0.9.exe", "rwd");
						raf.setLength(length);
						raf.close();
						// 平均每一个线程的大小
						int blockSize = length / threadCont;
						for (int threadId = 1; threadId <= threadCont; threadId++) {
							int startIndex = (threadId - 1) * blockSize;
							int endIndex = threadId * blockSize - 1;
							if (threadId == threadCont) {
								endIndex = length;
							}
							System.out.println("Thread :" + threadId + "下载"
									+ startIndex + "--->" + endIndex);
							new DownThread(threadId, startIndex, endIndex, path)
									.start();
						}

					} else {
						System.out.println("server error");
					}
				} catch (Exception e) {
					e.printStackTrace();
					Message m = new Message();
					m.what = 1;
					handler.sendMessage(m);
				}

			}
		}.start();
	}

	public class DownThread extends Thread {

		private int ThreadId;

		private int startIndex, endIndex;

		private String path;

		public DownThread(int threadId, int startIndex, int endIndex,
				String path) {
			this.ThreadId = threadId;
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.path = path;
		}

		public void run() {
			try {
				File tempFile = new File("/sdcard/" + ThreadId + ".txt");
				if (tempFile.exists() && tempFile.length() > 0) {
					FileInputStream fis1 = new FileInputStream(ThreadId
							+ ".txt");
					byte[] temp = new byte[1024];
					int leng = fis1.read(temp);
		
					String downLen = new String(temp, 0, leng);
					int iDownLoadLeng = Integer.parseInt(downLen);
					
					int alreadDown = iDownLoadLeng-startIndex;
					currentProcess+=alreadDown;
					
					startIndex = iDownLoadLeng;
					fis1.close();
				}

				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
						+ endIndex);
				System.out.println(ThreadId + "   :  真实下载" + startIndex + "-"
						+ endIndex);
				conn.setRequestMethod("GET");
				int code = conn.getResponseCode();// 如果请求全部资源200代表OK,请求部分资源,206代表OK
				System.out.println("code is " + code);
				InputStream is = conn.getInputStream();
				RandomAccessFile raf = new RandomAccessFile("/sdcard/"
						+ "cbox2.4.0.9.exe", "rwd");
				raf.seek(startIndex);
				int len = 0;
				byte[] buffer = new byte[1024];

				int total = 0;
				while ((len = is.read(buffer)) != -1) {
					RandomAccessFile file = new RandomAccessFile("/sdcard/"
							+ ThreadId + ".txt", "rwd");
					total += len;
					raf.write(buffer, 0, len);
					System.out.println("Thread " + ThreadId + "total is :"
							+ total);
					file.write(("" + (total + startIndex)).getBytes());
					synchronized (MainActivity.this) {
						currentProcess+=len;
						bar.setProgress(currentProcess);
						Message m = Message.obtain();
						m.what = TEXTVIEW_PROGRESS;
						handler.sendMessage(m);
					}
					
					file.close();
				}
				raf.close();
				System.out.println("thread" + ThreadId + "is downed");

			} catch (Exception e) {
				// TODO: handle exception
			} finally {
				finishThread();
			}
		}

		private synchronized void  finishThread() {
			deleteFileThread--;
			if (deleteFileThread == 0) {
				for (int i = 1; i <= threadCont; i++) {
					File delFile = new File("/sdcard/" + i + ".txt");
					delFile.delete();
				}
				System.out.println("临时文件删除完毕");
			}
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值