1.文件下载:
public void download(String<!--more--> urlString,String filename,String savePath) throws IOException {
//构造URL
URL url = new URL(urlString);
//打开链接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
//输入流
InputStream is = con.getInputStream();
//1k的缓冲数据
byte[] bs = new byte[1024];
//读取到的数据长度
int len;
File sf = new File(savePath);
if (sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename+".jpg");
//开始读数
while((len = is.read(bs)) != -1){
os.write(bs,0,len);
}
os.close();
is.close();
}
2.多线程
//批量创建实例
downpic[] arr = new downpic[threadNum];
//批量创建多线程
Thread[] thArr = new Thread[threadNum];
//给示例赋值
for (int i = 0; i < threadNum; i++) {
arr[i] = new downpic(picNum/threadNum*i,picNum/threadNum);
}
//批量开始线程
for (int i = 0; i < threadNum; i++) {
thArr[i] = new Thread(arr[i]);
thArr[i].start();
}