`

文件多线程下载

 
阅读更多

//线程下载类
package com.cgm.mutithreaddowm;

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

public class MutiThreadDowm {

public MutiThreadDowm() throws Exception{
     String path="http://localhost:8080/test/up/11.txt";
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
int code=con.getResponseCode();
if (code==200) {
int sum=con.getContentLength();

String fileName="d:/test/a.txt";
//创建一个空文件
RandomAccessFile file=new RandomAccessFile(new File(fileName), "rw");
file.setLength(sum);
file.close();

System.out.println(sum);
int threadCount=3;
int threadSize=sum/threadCount+(sum%threadCount==0?0:1);
for (int i = 0; i < threadCount; i++) {
int start=i*threadSize;
int end=start+(threadSize-1);
System.out.println("第"+(i+1)+"个线程要下载的值是"+start+"-"+end);
new MutiThread(url, fileName, start, end).start();  //开三个线程下载
}
}
con.disconnect();
}

public static void main(String[] args) throws Exception {
new MutiThreadDowm();
}

}




//线程类



package com.cgm.mutithreaddowm;

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

public class MutiThread extends Thread {
private URL  url;
private String fileName;
private int start;
private int end;

/*线程要知道服务文集N的URl
*  写到呢而去
*  从哪儿开始写
*  一共多少字节 数据
*/
public MutiThread(URL url, String fileName, int start, int end) {
//super();
this.url = url;
this.fileName = fileName;
this.start = start;
this.end = end;
}

@Override
public void run() {
HttpURLConnection con;
try {
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setRequestProperty("range", "bytes="+start+"-"+end);
con.connect();
int code=con.getResponseCode();
if (code==206) {
int size=con.getContentLength();
System.out.println(this.getName()+"下载的数据量是"+size);
RandomAccessFile file=new RandomAccessFile(new File(fileName),"rw");
InputStream in=con.getInputStream();
                file.seek(start);
                byte[] bts=new byte[1024];
                int len=0;
                while ((len=in.read(bts))!=-1) {
file.write(bts,0,len);
}
                file.close();
}
con.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}







}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics