public class Download {
public static int threadCount = 5; //线程开启的数量..
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://192.168.199.172:8080/jdk.exe";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int status = conn.getResponseCode();
if(status == 200){
int length = conn.getContentLength();
System.out.println(length);
int blocksize = length/threadCount; //将文件长度进行平分..
for(int threadID=1; threadID<=threadCount;threadID++){
int startIndex = (threadID-1)*blocksize; //开始位置的求法..
int endIndex = threadID*blocksize -1; //结束位置的求法..
/**
* 如果一个文件的长度无法整除线程数..
* 那么最后一个线程下载的结束位置需要设置文件末尾..
* */
if(threadID == threadCount){
endIndex = length;
}
System.out.println("线程下载位置:"+startIndex+"---"+endIndex);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//下载线程的定义..
public static class DownLoadThread implements Runnable{
private int threadID;
private int startIndex;
private int endIndex;
private String path;
public DownLoadThread(int threadID,int startIndex,int endIndex,String path){
this.threadID = threadID;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.path = path;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
//判断上一次是否下载完毕..如果没有下载完毕需要继续进行下载..这个文件记录了上一次的下载位置..
File tempfile =new File(threadID+".txt");
if(tempfile.exists() && tempfile.length()>0){
FileInputStream fis = new FileInputStream(tempfile);
byte buffer[] = new byte[1024];
int leng = fis.read(buffer);
int downlength = Integer.parseInt(new String(buffer,0,leng));//从上次下载后的位置开始下载..重新拟定开始下载的位置..
startIndex = downlength;
fis.close();
}
URL url = new URL(path);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
int status = conn.getResponseCode();
//206也表示服务器响应成功..
if(status == 206){
//获取服务器返回的I/O流..然后将数据写入文件当中..
InputStream in = conn.getInputStream();
//文件写入开始..用来保存当前需要下载的文件..
RandomAccessFile raf = new RandomAccessFile("jdk.exe", "rwd");
raf.seek(startIndex);
int len = 0;
byte buf[] =new byte[1024];
//记录已经下载的长度..
int total = 0;
while((len = in.read(buf))!=-1){
//用于记录当前下载的信息..
RandomAccessFile file =new RandomAccessFile(threadID+".txt", "rwd");
total += len;
file.write((total+startIndex+"").getBytes());
file.close();
//将数据写入文件当中..
raf.write(buf, 0, len);
}
in.close();
raf.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//如果所有的线程全部下载完毕后..也就是任务完成..清除掉所有原来的记录文件..
runningThread -- ;
if(runningThread==0){
for(int i=1;i<threadCount;i++){
File file = new File(i+".txt");
file.delete();
}
}
}
}
}
package com.example.mutithread;
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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et;
private ProgressBar pb;
public static int threadCount = 5;
public static int runningThread=5;
public int currentProgress=0; //当前进度值..
private TextView tv;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
switch (msg.what) {
case 1:
Toast.makeText(getApplicationContext(), msg.obj.toString(), 0).show();
break;
case 2:
break;
case 3:
tv.setText("当前进度:"+(pb.getProgress()*100)/pb.getMax());
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
pb =(ProgressBar) findViewById(R.id.pg);
tv= (TextView) findViewById(R.id.tv);
}
public void downLoad(View v){
final String path = et.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "下载路径错误", Toast.LENGTH_LONG).show();
return ;
}
new Thread(){
// String path = "http://192.168.199.172:8080/jdk.exe";
public void run(){
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int status = conn.getResponseCode();
if(status == 200){
int length = conn.getContentLength();
System.out.println("文件总长度"+length);
pb.setMax(length);
RandomAccessFile raf = new RandomAccessFile("/sdcard/setup.exe","rwd");
raf.setLength(length);
raf.close();
//开启5个线程来下载当前资源..
int blockSize = length/threadCount ;
for(int threadID=1;threadID<=threadCount;threadID++){
int startIndex = (threadID-1)*blockSize;
int endIndex = threadID*blockSize -1;
if(threadID == threadCount){
endIndex = length;
}
System.out.println("线程"+threadID+"下载:---"+startIndex+"--->"+endIndex);
new Thread(new DownLoadThread(threadID, startIndex, endIndex, path)).start() ;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
/**
* 下载线程..
* */
public class DownLoadThread implements Runnable{
private int ThreadID;
private int startIndex;
private int endIndex;
private String path;
public DownLoadThread(int ThreadID,int startIndex,int endIndex,String path){
this.ThreadID = ThreadID;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.path = path;
}
@Override
public void run() {
// TODO Auto-generated method stub
URL url;
try {
//检查是否存在还未下载完成的文件...
File tempfile = new File("/sdcard/"+ThreadID+".txt");
if(tempfile.exists() && tempfile.length()>0){
FileInputStream fis = new FileInputStream(tempfile);
byte temp[] =new byte[1024];
int leng = fis.read(temp);
int downlength = Integer.parseInt(new String(temp,0,leng));
int alreadydown = downlength -startIndex;
currentProgress += alreadydown;//发生断点之后记录下载的文件长度..
startIndex = downlength;
fis.close();
}
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
conn.setConnectTimeout(5000);
//获取响应码..
int status =conn.getResponseCode();
if(status == 206){
InputStream in = conn.getInputStream();
RandomAccessFile raf =new RandomAccessFile("/sdcard/jdk.exe", "rwd");
//文件开始写入..
raf.seek(startIndex);
int len =0;
byte[] buffer =new byte[1024];
//已经下载的数据长度..
int total = 0;
while((len = in.read(buffer))!=-1){
//记录当前数据下载的长度...
RandomAccessFile file = new RandomAccessFile("/sdcard/"+ThreadID+".txt", "rwd");
raf.write(buffer, 0, len);
total += len;
System.out.println("线程"+ThreadID+"total:"+total);
file.write((total+startIndex+"").getBytes());
file.close();
synchronized (MainActivity.this) {
currentProgress += len; //获取当前总进度...
//progressBar progressDialog可以直接在子线程内部更新UI..由于源码内部进行了特殊的处理..
pb.setProgress(currentProgress); //更改界面上的进度条进度..
Message msg =Message.obtain(); //复用以前的消息..避免多次new...
msg.what = 3;
handler.sendMessage(msg);
}
}
raf.close();
in.close();
System.out.println("线程:"+ThreadID+"下载完毕");
}else{
System.out.println("线程:"+ThreadID+"下载失败");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Message msg = new Message();
msg.what = 1;
msg.obj = e;
handler.sendMessage(msg);
}finally{
synchronized (MainActivity.this) {
runningThread--;
if(runningThread == 0){
for(int i=1;i<=threadCount;i++){
File file = new File("/sdcard/"+i+".txt");
file.delete();
}
Message msg =new Message();
msg.what = 2;
msg.obj ="下载完毕";
handler.sendMessage(msg);
}
}
}
}
}
@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;
}
}
private synchronized void refreshProgress(int id, int progress, boolean fromUser) {
if (mUiThreadId == Thread.currentThread().getId()) { //如果当前运行的线程和主线程相同..那么更新进度条..
doRefreshProgress(id, progress, fromUser, true);
} else { //如果不满足上面说的情况..
if (mRefreshProgressRunnable == null) {
mRefreshProgressRunnable = new RefreshProgressRunnable();//那么新建立一个线程..然后执行下面的过程..
}
final RefreshData rd = RefreshData.obtain(id, progress, fromUser); //获取消息队列中的消息..
mRefreshData.add(rd);
if (mAttached && !mRefreshIsPosted) {
post(mRefreshProgressRunnable); //主要是这个地方..调用了post方法..将当前运行的线程发送到消息队列当中..那么这个线程就可以在UI中运行了..因此这一步是决定因素..
mRefreshIsPosted = true;
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有