博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络_多线程下载
阅读量:4290 次
发布时间:2019-05-27

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

int threadCount=3;String url_st = "http://192.168.11.60:8080/mytry/FilePush?file=122.PNG";String file_path = "D:/zhang.png";			//连接网络,获得文件大小。URL url = new URL(url_st);HttpURLConnection http = (HttpURLConnection) url.openConnection();http.setRequestMethod("GET");http.setConnectTimeout(10000);int status = http.getResponseCode();if(status == 200){	int len = http.getContentLength();				//设置存储的位置	File file = new File(file_path);	RandomAccessFile raf = new RandomAccessFile(file, "rw");				//设置缓存文件大小。充大内容。	raf.setLength(len);	raf.close();	int blocksize = len/threadCount;	for(int i=0;i
class MyRunnable implements Runnable{	private String url_st;	private String file_path;	private int start;	private int end;	public MyRunnable(String url_st, String file_path, int start, int end) {		this.url_st = url_st;		this.file_path = file_path;		this.start = start;		this.end = end;		System.out.println(">>>>>>>>>开启一个新的线程。start:"+start+" end:"+end);	}	@Override	public void run() {		try {			URL url = new URL(url_st);			HttpURLConnection http = (HttpURLConnection) url.openConnection();			http.setRequestMethod("GET");			http.setRequestProperty("Range", "bytes="+start+"-"+end);			http.setConnectTimeout(10000);			//开始写			InputStream is = http.getInputStream();			RandomAccessFile raf = new RandomAccessFile(file_path,"rwd");			raf.seek(start);			byte[] buffer = new byte[1024*10];			int len =0;			while((len = is.read(buffer)) != -1){				raf.write(buffer, 0, len);				//标记写的位置,可以用来续传			}			raf.close();			http.disconnect();		} catch (MalformedURLException e) {			e.printStackTrace();		}catch(IOException e){			e.printStackTrace();		}	}}// 客户端进行 Range 网络请求,或者进行接收的 skip//输入流的: skip(long bytes);//由于skip不稳定,一般不直接使用public static void skipFully(InputStream is,long bytes) throws IOException{	long remaining = bytes;	long len = 0;	while(remaining > 0){		len = is.skip(remaining);		remaining -= len;	}}

转载地址:http://gbegi.baihongyu.com/

你可能感兴趣的文章
mysql中select * for update
查看>>
linux vmstat 1 ,watch , pmap -p,
查看>>
MYSQL 相关
查看>>
python 构建client 程序
查看>>
c++ 加载so动态库中的资源
查看>>
加解密 签名
查看>>
linux top 命令分析
查看>>
Linux vmstat命令详解
查看>>
linux pmap命令
查看>>
MySQL数据同步【双主热备】
查看>>
Mysql主从复制实践手册
查看>>
nginx配置正向代理支持HTTPS
查看>>
Perf -- Linux下的系统性能调优神器
查看>>
C++ 用libcurl库进行http通讯网络编程
查看>>
秒杀多线程第十篇 生产者消费者问题
查看>>
信号量与互斥锁
查看>>
linux 查看CPU个数,核数
查看>>
string 序列化
查看>>
va_start(),va_end()函数应用
查看>>
crontab命令
查看>>