您的位置:首页 > 编程语言 > Java开发

javase的多线程断点下载

2015-08-13 09:12 555 查看
-----------------------断点下载---------------------------

>DownloadThread extends Thread
//线程id
private int threadid;
private int startposition;
private int endposition;

DownloadThread(int ,int,int){
构造方法

}
run{
//断点下载之:判断是否已经下载过一部分的数据*********
File finfo = new File(threadid+".txt");
if(finfo.exists()&&finfo.length()>0){
FileInputReader fis = new FileInputStream(finfo);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String lastposition = br.readLine();
//这个现场上一次下载的大小
int intlastposition= Integer.parseInt(lastposition );
startPosition+=intlastposition;
fis.close();

}

URl url = new URL(path);

HttpURLConnection conn = (HttpURLConnection)
url.opneConnection();
conn.setRequestMethod("GET");
conn.setRequestPropertu("Range","bytes="+startPositeion+"-"+endPosition);
//从服务器下载资源
int code = conn.getResponseCode();//206 请求部分数据成功
if(code==206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");
//☆非常重要指定文件写的位置
raf.seek(startPosition);
byte[] buffer = new byte[1024*1024];//缓存区变成 1MB,缓存区越大,对硬盘的损耗就越小
int len = -1;
int total = 0;//当期线程这一次下载了多少
while((len=is.read(buffer))!=-1){
raf.write(buffer,0,len);
//断点下载之:把当期下载位置记录下来**************
total+=len;
RandomAccessFile inforaf = new RandomAccessFile(threadid+".txt","rwd");//每一次 数据都被同步到底
//层硬盘
inforaf.write(String.valueof(startposition+total).getBytes());
inforaf.close();

}
is.close();
raf.close():
syso("线程:"+threadid+"下载完毕了......");

}

}

>因为多线程分配是随机的,那么如何判断什么时候多线程下载完毕了呢

1.定义一个全局变量,一个标记位
1.private int runningThreadCount;
2.在线程循环是将其赋值为0,初始化
3.在抛出的异常//这里头要加一个同步锁
finally{
synchronize(MultiDownloader.class){
runningThreadCount--;
if(runningThreadCount<=0){
syso("多线程下载完毕了...恭喜恭喜");

}

}

}//从服务器下载资源
int code = conn.getResponseCode();//206 请求部分数据成功
if(code==206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");
//☆非常重要指定文件写的位置
raf.seek(startPosition);
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
raf.write(buffer,0,len);
//把当期下载位置记录下来

}
is.close();
raf.close():
syso("线程:"+threadid+"下载完毕了......");

}

}

--------------------------------------------------

优化:

1.根据路径获取文件名
public static String getDownLoadFileName(String path){
return path.substring(path.lastIndexof("/")+1);

}

2.对下载完成的文件将,记录日志给删除

for(int i=0;i<totalThreadCount;++i){
File f = new File(totalThreadCount+getDownLooadFileName(path)+i+".txt");
f.delete();

}

-----------------------------------------------------

ps:那这个javase的多线程断点下载敲会后,android下的多线程断点下载就只用改下包名和路径就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: