0
点赞
收藏
分享

微信扫一扫

Internet资源的断点续传实例

package com.web.test2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class TestDownLoad {

private long start = 0;
private long end = 0;

public TestDownLoad(long start,long end){
this.start = start;
this.end = end;
}

public TestDownLoad(long start){
this.start = start;
}

public TestDownLoad(){

}

public void down(){

try {
URL url = new URL("http://img05.tooopen.com/images/20140604/sy_62331342149.jpg");
URLConnection conn = url.openConnection();
/*设置请求参数*/
conn.setRequestProperty("User-Agent", "NetFox");
String sProperty = "bytes="+start+"-";
if (end > 0) {
sProperty = "bytes="+start+"-"+end;
}

conn.setRequestProperty("RANGE", sProperty);
conn.connect();

InputStream in = conn.getInputStream();
String file = url.getFile();
String name = file.substring(file.lastIndexOf("/")+1);
System.out.println(name);
//以追加的方式写文件
FileOutputStream fos = new FileOutputStream("F://"+name,true);
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b)) != -1){
fos.write(b, 0, len);
}
fos.close();
in.close();
conn.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("文件不存在");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
TestDownLoad d1 = new TestDownLoad(0,2000);
d1.down();
/*执行完d1的方法,再执行d2的方法,同时执行会并发下载,发生冲突*/
// TestDownLoad d2 = new TestDownLoad(2000);
// d2.down();

}
}


举报

相关推荐

0 条评论